{"size":12811,"ext":"cpp","lang":"C++","max_stars_count":140.0,"content":"\/*\r\nBullet Continuous Collision Detection and Physics Library\r\nCopyright (c) 2003-2009 Erwin Coumans http:\/\/bulletphysics.org\r\n\r\nThis software is provided 'as-is', without any express or implied warranty.\r\nIn no event will the authors be held liable for any damages arising from the use of this software.\r\nPermission is granted to anyone to use this software for any purpose, \r\nincluding commercial applications, and to alter it and redistribute it freely, \r\nsubject to the following restrictions:\r\n\r\n1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\r\n2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\r\n3. This notice may not be removed or altered from any source distribution.\r\n*\/\r\n\r\n\r\n#include \"btOptimizedBvh.h\"\r\n#include \"btStridingMeshInterface.h\"\r\n#include \"LinearMath\/btAabbUtil2.h\"\r\n#include \"LinearMath\/btIDebugDraw.h\"\r\n\r\n\r\nbtOptimizedBvh::btOptimizedBvh()\r\n{ \r\n}\r\n\r\nbtOptimizedBvh::~btOptimizedBvh()\r\n{\r\n}\r\n\r\n\r\nvoid btOptimizedBvh::build(btStridingMeshInterface* triangles, bool useQuantizedAabbCompression, const btVector3& bvhAabbMin, const btVector3& bvhAabbMax)\r\n{\r\n\tm_useQuantization = useQuantizedAabbCompression;\r\n\r\n\r\n\t\/\/ NodeArray\ttriangleNodes;\r\n\r\n\tstruct\tNodeTriangleCallback : public btInternalTriangleIndexCallback\r\n\t{\r\n\r\n\t\tNodeArray&\tm_triangleNodes;\r\n\r\n\t\tNodeTriangleCallback& operator=(NodeTriangleCallback& other)\r\n\t\t{\r\n\t\t\tm_triangleNodes.copyFromArray(other.m_triangleNodes);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t\t\r\n\t\tNodeTriangleCallback(NodeArray&\ttriangleNodes)\r\n\t\t\t:m_triangleNodes(triangleNodes)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tvirtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int triangleIndex)\r\n\t\t{\r\n\t\t\tbtOptimizedBvhNode node;\r\n\t\t\tbtVector3\taabbMin,aabbMax;\r\n\t\t\taabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));\r\n\t\t\taabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT)); \r\n\t\t\taabbMin.setMin(triangle[0]);\r\n\t\t\taabbMax.setMax(triangle[0]);\r\n\t\t\taabbMin.setMin(triangle[1]);\r\n\t\t\taabbMax.setMax(triangle[1]);\r\n\t\t\taabbMin.setMin(triangle[2]);\r\n\t\t\taabbMax.setMax(triangle[2]);\r\n\r\n\t\t\t\/\/with quantization?\r\n\t\t\tnode.m_aabbMinOrg = aabbMin;\r\n\t\t\tnode.m_aabbMaxOrg = aabbMax;\r\n\r\n\t\t\tnode.m_escapeIndex = -1;\r\n\t\r\n\t\t\t\/\/for child nodes\r\n\t\t\tnode.m_subPart = partId;\r\n\t\t\tnode.m_triangleIndex = triangleIndex;\r\n\t\t\tm_triangleNodes.push_back(node);\r\n\t\t}\r\n\t};\r\n\tstruct\tQuantizedNodeTriangleCallback : public btInternalTriangleIndexCallback\r\n\t{\r\n\t\tQuantizedNodeArray&\tm_triangleNodes;\r\n\t\tconst btQuantizedBvh* m_optimizedTree; \/\/ for quantization\r\n\r\n\t\tQuantizedNodeTriangleCallback& operator=(QuantizedNodeTriangleCallback& other)\r\n\t\t{\r\n\t\t\tm_triangleNodes.copyFromArray(other.m_triangleNodes);\r\n\t\t\tm_optimizedTree = other.m_optimizedTree;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tQuantizedNodeTriangleCallback(QuantizedNodeArray&\ttriangleNodes,const btQuantizedBvh* tree)\r\n\t\t\t:m_triangleNodes(triangleNodes),m_optimizedTree(tree)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tvirtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int triangleIndex)\r\n\t\t{\r\n\t\t\t\/\/ The partId and triangle index must fit in the same (positive) integer\r\n\t\t\tbtAssert(partId < (1<=0);\r\n\r\n\t\t\tbtQuantizedBvhNode node;\r\n\t\t\tbtVector3\taabbMin,aabbMax;\r\n\t\t\taabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));\r\n\t\t\taabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT)); \r\n\t\t\taabbMin.setMin(triangle[0]);\r\n\t\t\taabbMax.setMax(triangle[0]);\r\n\t\t\taabbMin.setMin(triangle[1]);\r\n\t\t\taabbMax.setMax(triangle[1]);\r\n\t\t\taabbMin.setMin(triangle[2]);\r\n\t\t\taabbMax.setMax(triangle[2]);\r\n\r\n\t\t\t\/\/PCK: add these checks for zero dimensions of aabb\r\n\t\t\tconst btScalar MIN_AABB_DIMENSION = btScalar(0.002);\r\n\t\t\tconst btScalar MIN_AABB_HALF_DIMENSION = btScalar(0.001);\r\n\t\t\tif (aabbMax.x() - aabbMin.x() < MIN_AABB_DIMENSION)\r\n\t\t\t{\r\n\t\t\t\taabbMax.setX(aabbMax.x() + MIN_AABB_HALF_DIMENSION);\r\n\t\t\t\taabbMin.setX(aabbMin.x() - MIN_AABB_HALF_DIMENSION);\r\n\t\t\t}\r\n\t\t\tif (aabbMax.y() - aabbMin.y() < MIN_AABB_DIMENSION)\r\n\t\t\t{\r\n\t\t\t\taabbMax.setY(aabbMax.y() + MIN_AABB_HALF_DIMENSION);\r\n\t\t\t\taabbMin.setY(aabbMin.y() - MIN_AABB_HALF_DIMENSION);\r\n\t\t\t}\r\n\t\t\tif (aabbMax.z() - aabbMin.z() < MIN_AABB_DIMENSION)\r\n\t\t\t{\r\n\t\t\t\taabbMax.setZ(aabbMax.z() + MIN_AABB_HALF_DIMENSION);\r\n\t\t\t\taabbMin.setZ(aabbMin.z() - MIN_AABB_HALF_DIMENSION);\r\n\t\t\t}\r\n\r\n\t\t\tm_optimizedTree->quantize(&node.m_quantizedAabbMin[0],aabbMin,0);\r\n\t\t\tm_optimizedTree->quantize(&node.m_quantizedAabbMax[0],aabbMax,1);\r\n\r\n\t\t\tnode.m_escapeIndexOrTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | triangleIndex;\r\n\r\n\t\t\tm_triangleNodes.push_back(node);\r\n\t\t}\r\n\t};\r\n\t\r\n\r\n\r\n\tint numLeafNodes = 0;\r\n\r\n\t\r\n\tif (m_useQuantization)\r\n\t{\r\n\r\n\t\t\/\/initialize quantization values\r\n\t\tsetQuantizationValues(bvhAabbMin,bvhAabbMax);\r\n\r\n\t\tQuantizedNodeTriangleCallback\tcallback(m_quantizedLeafNodes,this);\r\n\r\n\t\r\n\t\ttriangles->InternalProcessAllTriangles(&callback,m_bvhAabbMin,m_bvhAabbMax);\r\n\r\n\t\t\/\/now we have an array of leafnodes in m_leafNodes\r\n\t\tnumLeafNodes = m_quantizedLeafNodes.size();\r\n\r\n\r\n\t\tm_quantizedContiguousNodes.resize(2*numLeafNodes);\r\n\r\n\r\n\t} else\r\n\t{\r\n\t\tNodeTriangleCallback\tcallback(m_leafNodes);\r\n\r\n\t\tbtVector3 aabbMin(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));\r\n\t\tbtVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));\r\n\r\n\t\ttriangles->InternalProcessAllTriangles(&callback,aabbMin,aabbMax);\r\n\r\n\t\t\/\/now we have an array of leafnodes in m_leafNodes\r\n\t\tnumLeafNodes = m_leafNodes.size();\r\n\r\n\t\tm_contiguousNodes.resize(2*numLeafNodes);\r\n\t}\r\n\r\n\tm_curNodeIndex = 0;\r\n\r\n\tbuildTree(0,numLeafNodes);\r\n\r\n\t\/\/\/if the entire tree is small then subtree size, we need to create a header info for the tree\r\n\tif(m_useQuantization && !m_SubtreeHeaders.size())\r\n\t{\r\n\t\tbtBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand();\r\n\t\tsubtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[0]);\r\n\t\tsubtree.m_rootNodeIndex = 0;\r\n\t\tsubtree.m_subtreeSize = m_quantizedContiguousNodes[0].isLeafNode() ? 1 : m_quantizedContiguousNodes[0].getEscapeIndex();\r\n\t}\r\n\r\n\t\/\/PCK: update the copy of the size\r\n\tm_subtreeHeaderCount = m_SubtreeHeaders.size();\r\n\r\n\t\/\/PCK: clear m_quantizedLeafNodes and m_leafNodes, they are temporary\r\n\tm_quantizedLeafNodes.clear();\r\n\tm_leafNodes.clear();\r\n}\r\n\r\n\r\n\r\n\r\nvoid\tbtOptimizedBvh::refit(btStridingMeshInterface* meshInterface,const btVector3& aabbMin,const btVector3& aabbMax)\r\n{\r\n\tif (m_useQuantization)\r\n\t{\r\n\r\n\t\tsetQuantizationValues(aabbMin,aabbMax);\r\n\r\n\t\tupdateBvhNodes(meshInterface,0,m_curNodeIndex,0);\r\n\r\n\t\t\/\/\/now update all subtree headers\r\n\r\n\t\tint i;\r\n\t\tfor (i=0;i m_bvhAabbMin.getX());\r\n\tbtAssert(aabbMin.getY() > m_bvhAabbMin.getY());\r\n\tbtAssert(aabbMin.getZ() > m_bvhAabbMin.getZ());\r\n\r\n\tbtAssert(aabbMax.getX() < m_bvhAabbMax.getX());\r\n\tbtAssert(aabbMax.getY() < m_bvhAabbMax.getY());\r\n\tbtAssert(aabbMax.getZ() < m_bvhAabbMax.getZ());\r\n\r\n\t\/\/\/we should update all quantization values, using updateBvhNodes(meshInterface);\r\n\t\/\/\/but we only update chunks that overlap the given aabb\r\n\t\r\n\tunsigned short\tquantizedQueryAabbMin[3];\r\n\tunsigned short\tquantizedQueryAabbMax[3];\r\n\r\n\tquantize(&quantizedQueryAabbMin[0],aabbMin,0);\r\n\tquantize(&quantizedQueryAabbMax[0],aabbMax,1);\r\n\r\n\tint i;\r\n\tfor (i=0;im_SubtreeHeaders.size();i++)\r\n\t{\r\n\t\tbtBvhSubtreeInfo& subtree = m_SubtreeHeaders[i];\r\n\r\n\t\t\/\/PCK: unsigned instead of bool\r\n\t\tunsigned overlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax);\r\n\t\tif (overlap != 0)\r\n\t\t{\r\n\t\t\tupdateBvhNodes(meshInterface,subtree.m_rootNodeIndex,subtree.m_rootNodeIndex+subtree.m_subtreeSize,i);\r\n\r\n\t\t\tsubtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[subtree.m_rootNodeIndex]);\r\n\t\t}\r\n\t}\r\n\t\r\n}\r\n\r\nvoid\tbtOptimizedBvh::updateBvhNodes(btStridingMeshInterface* meshInterface,int firstNode,int endNode,int index)\r\n{\r\n\t(void)index;\r\n\r\n\tbtAssert(m_useQuantization);\r\n\r\n\tint curNodeSubPart=-1;\r\n\r\n\t\/\/get access info to trianglemesh data\r\n\t\tconst unsigned char *vertexbase = 0;\r\n\t\tint numverts = 0;\r\n\t\tPHY_ScalarType type = PHY_INTEGER;\r\n\t\tint stride = 0;\r\n\t\tconst unsigned char *indexbase = 0;\r\n\t\tint indexstride = 0;\r\n\t\tint numfaces = 0;\r\n\t\tPHY_ScalarType indicestype = PHY_INTEGER;\r\n\r\n\t\tbtVector3\ttriangleVerts[3];\r\n\t\tbtVector3\taabbMin,aabbMax;\r\n\t\tconst btVector3& meshScaling = meshInterface->getScaling();\r\n\t\t\r\n\t\tint i;\r\n\t\tfor (i=endNode-1;i>=firstNode;i--)\r\n\t\t{\r\n\r\n\r\n\t\t\tbtQuantizedBvhNode& curNode = m_quantizedContiguousNodes[i];\r\n\t\t\tif (curNode.isLeafNode())\r\n\t\t\t{\r\n\t\t\t\t\/\/recalc aabb from triangle data\r\n\t\t\t\tint nodeSubPart = curNode.getPartId();\r\n\t\t\t\tint nodeTriangleIndex = curNode.getTriangleIndex();\r\n\t\t\t\tif (nodeSubPart != curNodeSubPart)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (curNodeSubPart >= 0)\r\n\t\t\t\t\t\tmeshInterface->unLockReadOnlyVertexBase(curNodeSubPart);\r\n\t\t\t\t\tmeshInterface->getLockedReadOnlyVertexIndexBase(&vertexbase,numverts,\ttype,stride,&indexbase,indexstride,numfaces,indicestype,nodeSubPart);\r\n\r\n\t\t\t\t\tcurNodeSubPart = nodeSubPart;\r\n\t\t\t\t\tbtAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT);\r\n\t\t\t\t}\r\n\t\t\t\t\/\/triangles->getLockedReadOnlyVertexIndexBase(vertexBase,numVerts,\r\n\r\n\t\t\t\tunsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride);\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tfor (int j=2;j>=0;j--)\r\n\t\t\t\t{\r\n\t\t\t\t\t\r\n\t\t\t\t\tint graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j];\r\n\t\t\t\t\tif (type == PHY_FLOAT)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfloat* graphicsbase = (float*)(vertexbase+graphicsindex*stride);\r\n\t\t\t\t\t\ttriangleVerts[j] = btVector3(\r\n\t\t\t\t\t\t\tgraphicsbase[0]*meshScaling.getX(),\r\n\t\t\t\t\t\t\tgraphicsbase[1]*meshScaling.getY(),\r\n\t\t\t\t\t\t\tgraphicsbase[2]*meshScaling.getZ());\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble* graphicsbase = (double*)(vertexbase+graphicsindex*stride);\r\n\t\t\t\t\t\ttriangleVerts[j] = btVector3( btScalar(graphicsbase[0]*meshScaling.getX()), btScalar(graphicsbase[1]*meshScaling.getY()), btScalar(graphicsbase[2]*meshScaling.getZ()));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\r\n\t\t\t\taabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));\r\n\t\t\t\taabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT)); \r\n\t\t\t\taabbMin.setMin(triangleVerts[0]);\r\n\t\t\t\taabbMax.setMax(triangleVerts[0]);\r\n\t\t\t\taabbMin.setMin(triangleVerts[1]);\r\n\t\t\t\taabbMax.setMax(triangleVerts[1]);\r\n\t\t\t\taabbMin.setMin(triangleVerts[2]);\r\n\t\t\t\taabbMax.setMax(triangleVerts[2]);\r\n\r\n\t\t\t\tquantize(&curNode.m_quantizedAabbMin[0],aabbMin,0);\r\n\t\t\t\tquantize(&curNode.m_quantizedAabbMax[0],aabbMax,1);\r\n\t\t\t\t\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\t\/\/combine aabb from both children\r\n\r\n\t\t\t\tbtQuantizedBvhNode* leftChildNode = &m_quantizedContiguousNodes[i+1];\r\n\t\t\t\t\r\n\t\t\t\tbtQuantizedBvhNode* rightChildNode = leftChildNode->isLeafNode() ? &m_quantizedContiguousNodes[i+2] :\r\n\t\t\t\t\t&m_quantizedContiguousNodes[i+1+leftChildNode->getEscapeIndex()];\r\n\t\t\t\t\r\n\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int i=0;i<3;i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcurNode.m_quantizedAabbMin[i] = leftChildNode->m_quantizedAabbMin[i];\r\n\t\t\t\t\t\tif (curNode.m_quantizedAabbMin[i]>rightChildNode->m_quantizedAabbMin[i])\r\n\t\t\t\t\t\t\tcurNode.m_quantizedAabbMin[i]=rightChildNode->m_quantizedAabbMin[i];\r\n\r\n\t\t\t\t\t\tcurNode.m_quantizedAabbMax[i] = leftChildNode->m_quantizedAabbMax[i];\r\n\t\t\t\t\t\tif (curNode.m_quantizedAabbMax[i] < rightChildNode->m_quantizedAabbMax[i])\r\n\t\t\t\t\t\t\tcurNode.m_quantizedAabbMax[i] = rightChildNode->m_quantizedAabbMax[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tif (curNodeSubPart >= 0)\r\n\t\t\tmeshInterface->unLockReadOnlyVertexBase(curNodeSubPart);\r\n\r\n\t\t\r\n}\r\n\r\n\/\/\/deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place'\r\nbtOptimizedBvh* btOptimizedBvh::deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian)\r\n{\r\n\tbtQuantizedBvh* bvh = btQuantizedBvh::deSerializeInPlace(i_alignedDataBuffer,i_dataBufferSize,i_swapEndian);\r\n\t\r\n\t\/\/we don't add additional data so just do a static upcast\r\n\treturn static_cast(bvh);\r\n}\r\n","avg_line_length":32.681122449,"max_line_length":244,"alphanum_fraction":0.731246585} {"size":2511,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"\/*\n * Copyright (C) 2021 Huawei Device Co., Ltd.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"ap_interface.h\"\n#include \"wifi_ap_nat_manager.h\"\n\nnamespace OHOS {\nnamespace Wifi {\nApInterface::ApInterface()\n : m_ApRootState(),\n m_ApStartedState(m_ApStateMachine, m_ApConfigUse, m_ApMonitor),\n m_ApIdleState(m_ApStateMachine),\n m_ApMonitor(),\n m_ApStateMachine(m_ApStationsManager, m_ApRootState, m_ApIdleState, m_ApStartedState, m_ApMonitor),\n m_ApService(m_ApStateMachine),\n m_ApStationsManager(),\n m_ApConfigUse()\n{}\n\nApInterface::~ApInterface()\n{}\n\nextern \"C\" IApService *Create(void)\n{\n return new ApInterface();\n}\n\nextern \"C\" void Destroy(IApService *pservice)\n{\n delete pservice;\n}\nErrCode ApInterface::EnableHotspot()\n{\n return m_ApService.EnableHotspot();\n}\n\nErrCode ApInterface::DisableHotspot()\n{\n return m_ApService.DisableHotspot();\n}\n\nErrCode ApInterface::AddBlockList(const StationInfo &stationInfo)\n{\n return m_ApService.AddBlockList(stationInfo);\n}\n\nErrCode ApInterface::DelBlockList(const StationInfo &stationInfo)\n{\n return m_ApService.DelBlockList(stationInfo);\n}\n\nErrCode ApInterface::SetHotspotConfig(const HotspotConfig &hotspotConfig)\n{\n return m_ApService.SetHotspotConfig(hotspotConfig);\n}\n\nErrCode ApInterface::DisconnetStation(const StationInfo &stationInfo)\n{\n return m_ApService.DisconnetStation(stationInfo);\n}\n\nErrCode ApInterface::GetStationList(std::vector &result)\n{\n return m_ApService.GetStationList(result);\n}\n\nErrCode ApInterface::GetValidBands(std::vector &bands)\n{\n return m_ApService.GetValidBands(bands);\n}\n\nErrCode ApInterface::GetValidChannels(BandType band, std::vector &validchannel)\n{\n return m_ApService.GetValidChannels(band, validchannel);\n}\n\nErrCode ApInterface::RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks)\n{\n return m_ApService.RegisterApServiceCallbacks(callbacks);\n}\n} \/\/ namespace Wifi\n} \/\/ namespace OHOS","avg_line_length":27.0,"max_line_length":105,"alphanum_fraction":0.7614496217} {"size":969,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/\/https:\/\/leetcode.com\/problems\/kth-smallest-element-in-a-sorted-matrix\/\r\n\r\nint kthSmallest(vector>& matrix, int k) {\r\n \r\n \/\/O(1)agar all element in row is sorted and 1st element of next row is always greater then then \r\n \/\/last element of 1st row\r\n\/\/ int n=matrix.size();\r\n\r\n\/\/ int level=k\/n, traverse=k%n;\r\n\/\/ if(k%n!=0)\r\n\/\/ {\r\n\/\/ return matrix[level][traverse-1];\r\n\/\/ }\r\n\/\/ else\/\/ye shi h\r\n\/\/ return matrix[level-1][n-1];\r\n \r\n \r\n \/\/time O(M * N * logK), where M <= 300 is the number of rows, N <= 300 is the number of columns.\r\n \/\/Space: O(K)\r\n priority_queuepq;\r\n int n=matrix.size();\r\n for(int i=0;ik)pq.pop();\r\n }\r\n }\r\n return pq.top();\r\n }","avg_line_length":32.3,"max_line_length":105,"alphanum_fraction":0.4602683179} {"size":2043,"ext":"cpp","lang":"C++","max_stars_count":60.0,"content":"#include \"InitialItemSelector.hpp\"\n#include \"RNG.hpp\"\n\nusing namespace std;\n\npair InitialItemSelector::get_item_details(const string& race_id, const InitialItem& initial_item) const\n{\n string base_id = initial_item.get_item_id();\n uint quantity = RNG::dice(initial_item.get_item_quantity());\n\n \/\/ If there is a random ID, it gets used first:\n pair details = get_random_item_details(initial_item);\n \n if (!details.first.empty())\n {\n return details;\n }\n\n \/\/ If there is a racial ID, it overrides the base ID:\n details = get_racial_item_details(race_id, initial_item);\n\n if (!details.first.empty())\n {\n return details;\n }\n\n \/\/ There is neither a random ID nor a rcial ID, so return the base ID.\n details = make_pair(base_id, quantity);\n return details;\n}\n\n\/\/ Pick one of the random IDs, well, at random.\npair InitialItemSelector::get_random_item_details(const InitialItem& initial_item) const\n{\n pair random_details;\n\n vector> random_iis = initial_item.get_random_item_ids();\n\n if (!random_iis.empty())\n {\n pair random_ii = random_iis.at(RNG::range(0, random_iis.size()-1));\n \n random_details.first = random_ii.first;\n random_details.second = RNG::dice(random_ii.second);\n }\n\n return random_details;\n}\n\n\/\/ Pick the racial item ID that corresponds to the provided race ID.\n\/\/ If it doesn't exist, return an empty string.\npair InitialItemSelector::get_racial_item_details(const string& race_id, const InitialItem& initial_item) const\n{\n pair race_item_details;\n\n map> racial_ids = initial_item.get_racial_item_ids();\n map>::const_iterator i_it = racial_ids.find(race_id);\n\n if (i_it != racial_ids.end())\n {\n race_item_details.first = i_it->second.first;\n race_item_details.second = RNG::dice(i_it->second.second);\n }\n\n return race_item_details;\n}\n\n#ifdef UNIT_TESTS\n#include \"unit_tests\/InitialItemSelector_test.cpp\"\n#endif\n","avg_line_length":28.7746478873,"max_line_length":125,"alphanum_fraction":0.7342143906} {"size":5262,"ext":"cpp","lang":"C++","max_stars_count":4.0,"content":"\/**\r\n * Copyright (C) 2014 MongoDB Inc.\r\n *\r\n * This program is free software: you can redistribute it and\/or modify\r\n * it under the terms of the GNU Affero General Public License, version 3,\r\n * as published by the Free Software Foundation.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with this program. If not, see .\r\n *\r\n * As a special exception, the copyright holders give permission to link the\r\n * code of portions of this program with the OpenSSL library under certain\r\n * conditions as described in each individual source file and distribute\r\n * linked combinations including the program with the OpenSSL library. You\r\n * must comply with the GNU Affero General Public License in all respects for\r\n * all of the code used other than as permitted herein. If you modify file(s)\r\n * with this exception, you may extend this exception to your version of the\r\n * file(s), but you are not obligated to do so. If you do not wish to do so,\r\n * delete this exception statement from your version. If you delete this\r\n * exception statement from all source files in the program, then also delete\r\n * it in the license file.\r\n *\/\r\n\r\n#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault\r\n\r\n#include \"mongo\/platform\/basic.h\"\r\n\r\n#include \"mongo\/logger\/parse_log_component_settings.h\"\r\n\r\n#include \r\n\r\n#include \"mongo\/bson\/bsonobj.h\"\r\n#include \"mongo\/bson\/bsonobjbuilder.h\"\r\n#include \"mongo\/bson\/bsontypes.h\"\r\n#include \"mongo\/logger\/log_component.h\"\r\n#include \"mongo\/util\/assert_util.h\"\r\n#include \"mongo\/util\/log.h\"\r\n#include \"mongo\/util\/mongoutils\/str.h\"\r\n#include \"mongo\/util\/stringutils.h\"\r\n\r\nnamespace mongo {\r\nnamespace logger {\r\n\r\n\/*\r\n * Looks up a component by its short name, or returns kNumLogComponents\r\n * if the shortName is invalid\r\n *\/\r\nconst LogComponent _getComponentForShortName(StringData shortName) {\r\n for (int i = 0; i < int(LogComponent::kNumLogComponents); ++i) {\r\n LogComponent component = static_cast(i);\r\n if (component.getShortName() == shortName)\r\n return component;\r\n }\r\n return static_cast(LogComponent::kNumLogComponents);\r\n}\r\n\r\nStatusWith> parseLogComponentSettings(const BSONObj& settings) {\r\n typedef std::vector Result;\r\n\r\n std::vector levelsToSet;\r\n std::vector iterators;\r\n\r\n LogComponent parentComponent = LogComponent::kDefault;\r\n BSONObjIterator iter(settings);\r\n\r\n while (iter.moreWithEOO()) {\r\n BSONElement elem = iter.next();\r\n if (elem.eoo()) {\r\n if (!iterators.empty()) {\r\n iter = iterators.back();\r\n iterators.pop_back();\r\n parentComponent = parentComponent.parent();\r\n }\r\n continue;\r\n }\r\n if (elem.fieldNameStringData() == \"verbosity\") {\r\n if (!elem.isNumber()) {\r\n return StatusWith(ErrorCodes::BadValue,\r\n str::stream() << \"Expected \"\r\n << parentComponent.getDottedName()\r\n << \".verbosity to be a number, but found \"\r\n << typeName(elem.type()));\r\n }\r\n levelsToSet.push_back((LogComponentSetting(parentComponent, elem.numberInt())));\r\n continue;\r\n }\r\n const StringData shortName = elem.fieldNameStringData();\r\n const LogComponent curr = _getComponentForShortName(shortName);\r\n\r\n if (curr == LogComponent::kNumLogComponents || curr.parent() != parentComponent) {\r\n return StatusWith(\r\n ErrorCodes::BadValue,\r\n str::stream() << \"Invalid component name \" << parentComponent.getDottedName() << \".\"\r\n << shortName);\r\n }\r\n if (elem.isNumber()) {\r\n levelsToSet.push_back(LogComponentSetting(curr, elem.numberInt()));\r\n continue;\r\n }\r\n if (elem.type() != Object) {\r\n return StatusWith(ErrorCodes::BadValue,\r\n str::stream() << \"Invalid type \" << typeName(elem.type())\r\n << \"for component \"\r\n << parentComponent.getDottedName()\r\n << \".\"\r\n << shortName);\r\n }\r\n iterators.push_back(iter);\r\n parentComponent = curr;\r\n iter = BSONObjIterator(elem.Obj());\r\n }\r\n\r\n \/\/ Done walking settings\r\n return StatusWith(levelsToSet);\r\n}\r\n\r\n} \/\/ namespace logger\r\n} \/\/ namespace mongo\r\n","avg_line_length":42.435483871,"max_line_length":101,"alphanum_fraction":0.5961611555} {"size":546,"ext":"cpp","lang":"C++","max_stars_count":3.0,"content":"#include \"zad5_a.cpp\"\r\n#include \"zad5_b.cpp\"\r\n#include \"zad5_c.cpp\"\r\n#include \"zad5_d.cpp\"\r\n#include \r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n cout << zad5_a() << endl\r\n << endl\r\n << zad5_b() << endl\r\n << endl\r\n << zad5_c() << endl\r\n << endl\r\n << zad5_d() << endl;\r\n\r\n ofstream result(\"wyniki.txt\");\r\n\r\n result << zad5_a() << endl\r\n << endl\r\n << zad5_b() << endl\r\n << endl\r\n << zad5_c() << endl\r\n << endl\r\n << zad5_d() << endl;\r\n}\r\n","avg_line_length":19.5,"max_line_length":35,"alphanum_fraction":0.4377289377} {"size":7779,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n#include \n#include \n#include \n#include \"IntcodeComputer.h\"\n#include \"Screen.h\"\n#include \"vector\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct Pos {\n int x;\n int y;\n Pos move(int direction) const {\n Pos result {x, y};\n switch (direction) {\n case 0:\n result.y -=1;\n break;\n case 1:\n result.x +=1;\n break;\n case 2:\n result.y +=1;\n break;\n case 3:\n result.x -=1;\n break;\n }\n return result;\n }\n\n bool operator==(const Pos &other) const{\n return x == other.x && y == other.y;\n }\n\n bool operator!=(const Pos &other) const{\n return x != other.x || y != other.y;\n }\n};\n\n\/\/ Required by unordered_map\ntemplate<> struct std::hash {\n std::size_t operator() (const Pos &node) const {\n return (hash()(node.x) << 4) ^ hash()(node.y);\n }\n};\n\n\nstruct State {\n string path;\n vector program;\n vector commands;\n bool is_valid;\n};\n\nint command_length(string command);\nstd::string steps_to_str(int steps);\nState solve(State state);\n\n\n\nstring inputs = \"\";\nint inp_pos = 0;\nlong on_input() {\n long result = inputs[inp_pos++];\n return result;\n}\n\nIntcodeComputer computer;\n\nint main() {\n Screen screen;\n computer.load_program(\"program.txt\");\n\n std::unordered_map map;\n\n int x=1;\n int y=1;\n Pos robot;\n screen.cls();\n while (!computer.is_halted()) {\n while (!computer.step(false, on_input)) {\n ;\n }\n char ch = computer.get_last_output();\n Pos pos {x, y};\n if (ch == '#') {\n map[pos] = 1;\n }\n if (ch == '^') {\n robot = pos;\n }\n if (ch != 10) {\n screen.text(x, y, std::string(1,ch));\n }\n if (ch == 10) {\n y++;\n x=1;\n }\n else {\n x++;\n }\n }\n int rows = y+1;\n int cols = x+1;\n\n int sum = 0;\n\n\n for (const auto &pair: map) {\n auto &pos = pair.first;\n if (pos.x == 0 || pos.y == 0 || pos.x == cols-1 || pos.y == rows -1) {\n continue;\n }\n bool is_intersection = true;\n for (int dir = 0; dir < 4; dir++) {\n auto neighbour = pos.move(dir);\n if (!map.count(neighbour)) {\n is_intersection = false;\n break;\n }\n }\n if (is_intersection) {\n sum+= pos.x * pos.y;\n }\n }\n\n screen.text(1,40, \" \");\n std::cout << std::endl << \"Sum of the alignment parameters: \" << sum << std::endl;\n\n\n std::string path;\n int dir = 0;\n Pos robot_pos = robot;\n do {\n int steps = 0;\n auto forward = robot_pos.move(dir);\n\n while (map.count(forward)) {\n robot_pos = forward;\n steps++;\n forward = robot_pos.move(dir);\n }\n if (steps) {\n path += steps_to_str(steps);\n }\n\n auto left = robot_pos.move((dir+3) % 4);\n if (map.count(left)) {\n path+=\"L\";\n dir = (dir+3) % 4;\n continue;\n }\n auto right = robot_pos.move((dir+1) % 4);\n if (map.count(right)) {\n path+=\"R\";\n dir = (dir+1) % 4;\n continue;\n }\n break;\n } while(true);\n\n std::cout << \"Path: \" << path << std::endl;\n\n State state;\n state.path = path;\n state.is_valid = false;\n state.program.clear();\n state.commands.clear();\n\n State solution = solve(state);\n if (!solution.is_valid) {\n cout << \"Solition not found!\" << endl;\n return -1;\n }\n\n\n\n\n string program = std::accumulate(\n solution.program.begin(),\n solution.program.end(),\n string(),\n [](string &acc, string &code) {\n return acc.empty() ? code : acc + \",\" + code;\n });\n inputs += program + '\\x0A';\n\n\n for (const string &command : solution.commands) {\n string command_str = std::accumulate(\n command.begin(),\n command.end(),\n string(),\n [](string &acc, const char &code) {\n string st;\n if (code == 's') {\n st = \"6\";\n } else if (code == 'e') {\n st = \"8\";\n } else if (code == 't') {\n st = \"12\";\n } else {\n st = code;\n }\n return acc.empty() ? st : acc + \",\" + st;\n });\n inputs += command_str + '\\x0A';\n }\n\n computer.load_program(\"program.txt\");\n\/\/ computer.reset();\n computer.ram[0] = 2; \/\/ wake the vacuum robot\n\n inputs += \"n\"; \/\/ np video\n\n while (!computer.is_halted()) {\n\n bool out = computer.step(false, on_input);\n if (out) {\n auto last = computer.get_last_output();\n if (last > 256) {\n cout << \"Vacuum robot report: \" << last << endl;\n break;\n }\n }\n }\n\n return 0;\n\n}\n\nState solve(State state) {\n\n\n \/\/ Try re-use existing commands\n if (state.program.size() < 20 && !state.commands.empty()) {\n for (int i = 0; i < state.commands.size(); i++) {\n string command = state.commands[i];\n if (command == state.path) {\n state.program.push_back( string(1, 'A' + i));\n state.is_valid = true;\n return state;\n }\n if (state.path.rfind(command, 0) == 0) { \/\/ remaining path starts with a command\n\n State newState {\n state.path.substr(command.length(), 1000),\n state.program,\n state.commands,\n false,\n };\n newState.program.push_back( string(1, 'A' + i));\n State res = solve(newState);\n if (res.is_valid) {\n return res;\n }\n }\n }\n }\n\n \/\/ Try add new command\n if (state.commands.size() < 3) {\n for (int com_length = 2; com_length <= state.path.size(); com_length+=2) {\n auto candidate = state.path.substr(0, com_length);\n\n if (find(state.commands.begin(), state.commands.end(), candidate) != state.commands.end()) {\n \/\/command already in the list, skip it\n continue;\n }\n if (command_length(candidate) <= 20) {\n State newState {\n state.path,\n state.program,\n state.commands,\n false,\n };\n newState.commands.push_back(candidate);\n State res = solve(newState);\n if (res.is_valid) {\n return res;\n }\n }\n else {\n break;\n }\n }\n }\n state.is_valid = false;\n return state;\n}\n\nstd::string steps_to_str(int steps) {\n switch (steps) {\n case 6:\n return \"s\";\n case 8:\n return \"e\";\n case 12:\n return \"t\";\n default:\n return \"?\";\n }\n}\n\nint command_length(string command) {\n int result = 0;\n for (const auto &ch: command) {\n if (ch == 't') {\n result +=3;\n }\n else {\n result+=2;\n }\n }\n return result - 1; \/\/ do not include last comma\n}","avg_line_length":24.1583850932,"max_line_length":104,"alphanum_fraction":0.4437588379} {"size":345,"ext":"hpp","lang":"C++","max_stars_count":4.0,"content":"\/\/\n\/\/ Misc.h\n\/\/ GrooveCoasterRE\n\/\/\n\/\/ Created by Zhang Naville on 15\/9\/4.\n\/\/ Copyright \u00a9 2015\u5e74 Naville. All rights reserved.\n\/\/\n\n#ifndef Misc_h\n#define Misc_h\n\n#include \n#include \n\n#endif \/* Misc_h *\/\n\/\/----- (000999E8) --------------------------------------------------------\nvoid loadSaveFileNS(const char *a1, int *a2);","avg_line_length":20.2941176471,"max_line_length":75,"alphanum_fraction":0.547826087} {"size":3875,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/* ------------------------------------------------------------------\n Copyright (c) 2011-2020 Marc Toussaint\n email: toussaint@tu-berlin.de\n\n This code is distributed under the MIT License.\n Please see \/LICENSE for details.\n -------------------------------------------------------------- *\/\n\n#include \"F_geometrics.h\"\n\n#include \"F_collisions.h\"\n#include \"F_pose.h\"\n#include \"frame.h\"\n\n\/\/===========================================================================\n\nvoid F_AboveBox::phi2(arr& y, arr& J, const FrameL& F) {\n CHECK_EQ(order, 0, \"\");\n CHECK_EQ(F.N, 2, \"\");\n\n rai::Shape* box=F.elem(0)->shape;\n CHECK(box, \"I need a shape as second frame!\");\n CHECK_EQ(box->type(), rai::ST_ssBox, \"the 2nd shape needs to be a box\"); \/\/s1 should be the board\n Value pos = F_PositionRel()\n .eval({F.elem(1), F.elem(0)}); \/\/TODO - that's somewhat awkward?\n arr proj({2,3}, {1,0,0,0,1,0});\n pos.y = proj * pos.y;\n pos.J = proj * pos.J;\n arr range = { .5*box->size(0)-margin, .5*box->size(1)-margin };\n\n y.setBlockVector(pos.y - range, -pos.y - range);\n J.setBlockMatrix(pos.J, -pos.J);\n}\n\n\/\/===========================================================================\n\n\nvoid F_InsideBox::phi2(arr& y, arr& J, const FrameL& F) {\n CHECK_EQ(F.N, 2, \"\");\n rai::Frame* pnt=F.elem(0);\n rai::Frame* box=F.elem(1);\n CHECK(box->shape, \"I need shapes!\");\n CHECK(box->shape->type()==rai::ST_ssBox, \"the 2nd shape needs to be a box\"); \/\/s1 should be the board\n\/\/ arr pos, posJ;\n\/\/ G.kinematicsRelPos(pos, posJ, &pnt->frame, ivec, &box->frame, NoVector);\n Value pos = F_PositionRel() .eval({pnt, box});\n arr range = box->shape->size();\n range *= .5;\n range -= margin;\n for(double& r:range) if(r<.01) r=.01;\n\n pnt->C.kinematicsZero(y, J, 6);\n\n y(0) = pos.y(0) - range(0);\n y(1) = pos.y(1) - range(1);\n y(2) = pos.y(2) - range(2);\n y(3) = -pos.y(0) - range(0);\n y(4) = -pos.y(1) - range(1);\n y(5) = -pos.y(2) - range(2);\n\n if(!!J) J.setBlockMatrix(pos.J, -pos.J);\n}\n\n\/\/===========================================================================\n\nvoid TM_InsideLine::phi2(arr& y, arr& J, const FrameL& F) {\n CHECK_EQ(F.N, 2, \"\");\n rai::Shape* pnt=F.elem(0)->shape;\n rai::Shape* box=F.elem(1)->shape;\n CHECK(pnt && box, \"I need shapes!\");\n CHECK(box->type()==rai::ST_capsule, \"the 2nd shape needs to be a capsule\"); \/\/s1 should be the board\n\/\/ arr pos, posJ;\n\/\/ G.kinematicsRelPos(pos, posJ, &pnt->frame, NoVector, &box->frame, NoVector);\n Value pos = evalFeature({&pnt->frame, &box->frame});\n double range = box->size(-2);\n range *= .5;\n range -= margin;\n if(range<.01) range=.01;\n\n y.resize(2);\n y(0) = pos.y(2) - range;\n y(1) = -pos.y(2) - range;\n if(!!J) {\n J.resize(2, pos.J.d1);\n CHECK(!isSpecial(pos.J), \"\");\n J[0] = pos.J[2];\n J[1] = -pos.J[2];\n }\n}\n\n\/\/===========================================================================\n\nvoid F_GraspOppose::phi2(arr& y, arr& J, const FrameL& F) {\n CHECK_EQ(order, 0, \"\");\n CHECK_EQ(F.N, 3, \"\");\n Value D1 = F_PairCollision(F_PairCollision::_vector, true)\n .eval({F.elem(0), F.elem(2)});\n Value D2 = F_PairCollision(F_PairCollision::_vector, true)\n .eval({F.elem(1), F.elem(2)});\n\n\n if(!centering) {\n y = D1.y + D2.y;\n if(!!J) J = D1.J + D2.J;\n }else{\n normalizeWithJac(D1.y, D1.J);\n normalizeWithJac(D2.y, D2.J);\n\n Value P1 = F_Position() .eval({F.elem(0)});\n Value P2 = F_Position() .eval({F.elem(1)});\n\n arr P = 2.*eye(3) - (D1.y*~D1.y) - (D2.y*~D2.y);\n arr p = P2.y - P1.y;\n double scale = 1e-1;\n\n arr cen, cenJ;\n cen = scale * (P * p);\n if(!!J) cenJ = P * (P2.J-P1.J) - (D1.J*scalarProduct(D1.y, p) + D1.y*(~p*D1.J)) - (D2.J*scalarProduct(D2.y, p) + D2.y*(~p*D2.J));\n\n y.setBlockVector(D1.y + D2.y, cen);\n J.setBlockMatrix(D1.J + D2.J, cenJ);\n }\n}\n\n\n\n","avg_line_length":30.5118110236,"max_line_length":133,"alphanum_fraction":0.5091612903} {"size":4776,"ext":"cc","lang":"C++","max_stars_count":2.0,"content":"\/\/ Copyright 2021 Peng Huang \n\/\/ This file is part of Wallet-core-python.\n\/\/\n\/\/ Wallet-core-python is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ Wallet-core-python is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with Wallet-core-python. If not, see .\n\/\/\n\/\/ NOTE: this is a GENERATED FILE, changes made here WILL BE LOST.\n\n#include \"generated\/FIOAccount.h\"\n\n\n#include \"String.h\"\n#include \"String.h\"\n\n\nstruct PyFIOAccountObject {\n PyObject_HEAD;\n TWFIOAccount* value;\n};\n\nstatic PyTypeObject PyFIOAccountType = {\n \/\/ clang-format off\n PyVarObject_HEAD_INIT(NULL, 0)\n \/\/ clang-format on\n \"walletcore.FIOAccount\", \/* tp_name *\/\n sizeof(PyFIOAccountObject), \/* tp_basicsize *\/\n 0, \/* tp_itemsize *\/\n 0, \/* tp_dealloc *\/\n 0, \/* tp_print *\/\n 0, \/* tp_getattr *\/\n 0, \/* tp_setattr *\/\n 0, \/* tp_reserved *\/\n 0, \/* tp_repr *\/\n 0, \/* tp_as_number *\/\n 0, \/* tp_as_sequence *\/\n 0, \/* tp_as_mapping *\/\n 0, \/* tp_hash *\/\n 0, \/* tp_call *\/\n 0, \/* tp_str *\/\n 0, \/* tp_getattro *\/\n 0, \/* tp_setattro *\/\n 0, \/* tp_as_buffer *\/\n Py_TPFLAGS_DEFAULT, \/* tp_flags *\/\n nullptr, \/* tp_doc *\/\n};\n\n\nbool PyFIOAccount_Check(PyObject* object) {\n return PyObject_TypeCheck(object, &PyFIOAccountType) != 0;\n}\n\n\/\/ Create PyFIOAccount from enum TWFIOAccount.\nPyObject* PyFIOAccount_FromTWFIOAccount(TWFIOAccount* value) {\n if (!value)\n Py_RETURN_NONE;\n\n PyFIOAccountObject* object = PyObject_New(PyFIOAccountObject, &PyFIOAccountType);\n if (!object)\n return nullptr;\n\n object->value = value;\n\n return (PyObject*)object;\n}\n\nTWFIOAccount* PyFIOAccount_GetTWFIOAccount(PyObject* object) {\n assert(PyFIOAccount_Check(object));\n return ((PyFIOAccountObject*)object)->value;\n}\n\nstatic void PyFIOAccount_dealloc(PyFIOAccountObject *self) {\n if (self->value) {\n TWFIOAccountDelete(self->value);\n }\n Py_TYPE(self)->tp_free(self);\n}\n\n\n\n\/\/ getter function for Description\nstatic const char PyFIOAccountDescription_doc[] =\n \"TWString* TWFIOAccountDescription(struct TWFIOAccount* account)\";\nstatic PyObject* PyFIOAccountDescription(PyFIOAccountObject *self, void *) {\n TWStringPtr prop(TWFIOAccountDescription(self->value));\n return PyUnicode_FromTWString(prop);\n}\n\n\n\/\/ static method function for CreateWithString\nstatic const char PyFIOAccountCreateWithString_doc[] =\n \"struct TWFIOAccount* TWFIOAccountCreateWithString(TWString* string)\";\nstatic PyObject* PyFIOAccountCreateWithString(PyFIOAccountObject *self,\n PyObject *const *args,\n Py_ssize_t nargs) {\n \n if (nargs != 1) {\n PyErr_Format(PyExc_TypeError, \"Expect 1 args, but %d args are passed in.\", nargs);\n return nullptr;\n }\n\n\n if (!PyUnicode_Check(args[0])) {\n PyErr_SetString(PyExc_TypeError, \"The arg 0 is not in type Unicode\");\n return nullptr;\n }\n auto arg0 = PyUnicode_GetTWString(args[0]);\n\n TWFIOAccount* result = TWFIOAccountCreateWithString(arg0.get());\n return PyFIOAccount_FromTWFIOAccount(result);\n}\n\n\n\/\/ properties\n\n\nstatic const PyGetSetDef get_set_defs[] = {{ \"description\", (getter)PyFIOAccountDescription, nullptr, PyFIOAccountDescription_doc },{}\n};\n\nstatic const PyMethodDef method_defs[] = {{ \"create_with_string\", (PyCFunction)PyFIOAccountCreateWithString, METH_FASTCALL | METH_STATIC, PyFIOAccountCreateWithString_doc },{}\n};\n\nbool PyInit_FIOAccount(PyObject *module) {\n PyFIOAccountType.tp_dealloc = (destructor)PyFIOAccount_dealloc;\n PyFIOAccountType.tp_getset = (PyGetSetDef*)get_set_defs;\n PyFIOAccountType.tp_methods = (PyMethodDef*)method_defs;\n\n if (PyType_Ready(&PyFIOAccountType) < 0)\n return false;\n\n Py_INCREF(&PyFIOAccountType);\n if (PyModule_AddObject(module, \"FIOAccount\", (PyObject *) &PyFIOAccountType) < 0) {\n Py_DECREF(&PyFIOAccountType);\n return false;\n }\n\n return true;\n}","avg_line_length":32.4897959184,"max_line_length":175,"alphanum_fraction":0.6465661642} {"size":44598,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"\/*************************************************************************\/\n\/* mesh_instance.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"mesh_instance.h\"\n\n#include \"collision_shape.h\"\n#include \"core\/core_string_names.h\"\n#include \"core\/project_settings.h\"\n#include \"physics_body.h\"\n#include \"scene\/resources\/material.h\"\n#include \"scene\/scene_string_names.h\"\n#include \"servers\/visual\/visual_server_globals.h\"\n#include \"skeleton.h\"\n\nbool MeshInstance::_set(const StringName &p_name, const Variant &p_value) {\n\t\/\/this is not _too_ bad performance wise, really. it only arrives here if the property was not set anywhere else.\n\t\/\/add to it that it's probably found on first call to _set anyway.\n\n\tif (!get_instance().is_valid()) {\n\t\treturn false;\n\t}\n\n\tMap::Element *E = blend_shape_tracks.find(p_name);\n\tif (E) {\n\t\tE->get().value = p_value;\n\t\tVisualServer::get_singleton()->instance_set_blend_shape_weight(get_instance(), E->get().idx, E->get().value);\n\t\treturn true;\n\t}\n\n\tif (p_name.operator String().begins_with(\"material\/\")) {\n\t\tint idx = p_name.operator String().get_slicec('\/', 1).to_int();\n\t\tif (idx >= materials.size() || idx < 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tset_surface_material(idx, p_value);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool MeshInstance::_get(const StringName &p_name, Variant &r_ret) const {\n\tif (!get_instance().is_valid()) {\n\t\treturn false;\n\t}\n\n\tconst Map::Element *E = blend_shape_tracks.find(p_name);\n\tif (E) {\n\t\tr_ret = E->get().value;\n\t\treturn true;\n\t}\n\n\tif (p_name.operator String().begins_with(\"material\/\")) {\n\t\tint idx = p_name.operator String().get_slicec('\/', 1).to_int();\n\t\tif (idx >= materials.size() || idx < 0) {\n\t\t\treturn false;\n\t\t}\n\t\tr_ret = materials[idx];\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid MeshInstance::_get_property_list(List *p_list) const {\n\tList ls;\n\tfor (const Map::Element *E = blend_shape_tracks.front(); E; E = E->next()) {\n\t\tls.push_back(E->key());\n\t}\n\n\tls.sort();\n\n\tfor (List::Element *E = ls.front(); E; E = E->next()) {\n\t\tp_list->push_back(PropertyInfo(Variant::REAL, E->get(), PROPERTY_HINT_RANGE, \"-1,1,0.00001\"));\n\t}\n\n\tif (mesh.is_valid()) {\n\t\tfor (int i = 0; i < mesh->get_surface_count(); i++) {\n\t\t\tp_list->push_back(PropertyInfo(Variant::OBJECT, \"material\/\" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, \"ShaderMaterial,SpatialMaterial\"));\n\t\t}\n\t}\n}\n\nvoid MeshInstance::set_mesh(const Ref &p_mesh) {\n\tif (mesh == p_mesh) {\n\t\treturn;\n\t}\n\n\tif (mesh.is_valid()) {\n\t\tmesh->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed);\n\t}\n\n\tif (skin_ref.is_valid() && mesh.is_valid() && _is_software_skinning_enabled() && is_visible_in_tree()) {\n\t\tERR_FAIL_COND(!skin_ref->get_skeleton_node());\n\t\tskin_ref->get_skeleton_node()->disconnect(\"skeleton_updated\", this, \"_update_skinning\");\n\t}\n\n\tif (software_skinning) {\n\t\tmemdelete(software_skinning);\n\t\tsoftware_skinning = nullptr;\n\t}\n\n\tmesh = p_mesh;\n\n\tblend_shape_tracks.clear();\n\tif (mesh.is_valid()) {\n\t\tfor (int i = 0; i < mesh->get_blend_shape_count(); i++) {\n\t\t\tBlendShapeTrack mt;\n\t\t\tmt.idx = i;\n\t\t\tmt.value = 0;\n\t\t\tblend_shape_tracks[\"blend_shapes\/\" + String(mesh->get_blend_shape_name(i))] = mt;\n\t\t}\n\n\t\tmesh->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed);\n\t\tmaterials.resize(mesh->get_surface_count());\n\n\t\t_initialize_skinning(false, false);\n\t} else {\n\t\tset_base(RID());\n\t}\n\n\tupdate_gizmo();\n\n\t_change_notify();\n}\nRef MeshInstance::get_mesh() const {\n\treturn mesh;\n}\n\nvoid MeshInstance::_resolve_skeleton_path() {\n\tRef new_skin_reference;\n\n\tif (!skeleton_path.is_empty()) {\n\t\tSkeleton *skeleton = Object::cast_to(get_node(skeleton_path));\n\t\tif (skeleton) {\n\t\t\tnew_skin_reference = skeleton->register_skin(skin_internal);\n\t\t\tif (skin_internal.is_null()) {\n\t\t\t\t\/\/a skin was created for us\n\t\t\t\tskin_internal = new_skin_reference->get_skin();\n\t\t\t\t_change_notify();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (skin_ref.is_valid() && mesh.is_valid() && _is_software_skinning_enabled() && is_visible_in_tree()) {\n\t\tERR_FAIL_COND(!skin_ref->get_skeleton_node());\n\t\tskin_ref->get_skeleton_node()->disconnect(\"skeleton_updated\", this, \"_update_skinning\");\n\t}\n\n\tskin_ref = new_skin_reference;\n\n\tsoftware_skinning_flags &= ~SoftwareSkinning::FLAG_BONES_READY;\n\n\t_initialize_skinning();\n}\n\nbool MeshInstance::_is_global_software_skinning_enabled() {\n\t\/\/ Check if forced in project settings.\n\tif (GLOBAL_GET(\"rendering\/quality\/skinning\/force_software_skinning\")) {\n\t\treturn true;\n\t}\n\n\t\/\/ Check if enabled in project settings.\n\tif (!GLOBAL_GET(\"rendering\/quality\/skinning\/software_skinning_fallback\")) {\n\t\treturn false;\n\t}\n\n\t\/\/ Check if requested by renderer settings.\n\treturn VSG::storage->has_os_feature(\"skinning_fallback\");\n}\n\nbool MeshInstance::_is_software_skinning_enabled() const {\n\t\/\/ Using static local variable which will be initialized only once,\n\t\/\/ so _is_global_software_skinning_enabled can be only called once on first use.\n\tstatic bool global_software_skinning = _is_global_software_skinning_enabled();\n\treturn global_software_skinning;\n}\n\nvoid MeshInstance::_initialize_skinning(bool p_force_reset, bool p_call_attach_skeleton) {\n\tif (mesh.is_null()) {\n\t\treturn;\n\t}\n\n\tVisualServer *visual_server = VisualServer::get_singleton();\n\n\tbool update_mesh = false;\n\n\tif (skin_ref.is_valid()) {\n\t\tif (_is_software_skinning_enabled()) {\n\t\t\tif (is_visible_in_tree()) {\n\t\t\t\tERR_FAIL_COND(!skin_ref->get_skeleton_node());\n\t\t\t\tif (!skin_ref->get_skeleton_node()->is_connected(\"skeleton_updated\", this, \"_update_skinning\")) {\n\t\t\t\t\tskin_ref->get_skeleton_node()->connect(\"skeleton_updated\", this, \"_update_skinning\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (p_force_reset && software_skinning) {\n\t\t\t\tmemdelete(software_skinning);\n\t\t\t\tsoftware_skinning = nullptr;\n\t\t\t}\n\n\t\t\tif (!software_skinning) {\n\t\t\t\tsoftware_skinning = memnew(SoftwareSkinning);\n\n\t\t\t\tif (mesh->get_blend_shape_count() > 0) {\n\t\t\t\t\tERR_PRINT(\"Blend shapes are not supported for software skinning.\");\n\t\t\t\t}\n\n\t\t\t\tRef software_mesh;\n\t\t\t\tsoftware_mesh.instance();\n\t\t\t\tRID mesh_rid = software_mesh->get_rid();\n\n\t\t\t\t\/\/ Initialize mesh for dynamic update.\n\t\t\t\tint surface_count = mesh->get_surface_count();\n\t\t\t\tsoftware_skinning->surface_data.resize(surface_count);\n\t\t\t\tfor (int surface_index = 0; surface_index < surface_count; ++surface_index) {\n\t\t\t\t\tERR_CONTINUE(Mesh::PRIMITIVE_TRIANGLES != mesh->surface_get_primitive_type(surface_index));\n\n\t\t\t\t\tSoftwareSkinning::SurfaceData &surface_data = software_skinning->surface_data[surface_index];\n\t\t\t\t\tsurface_data.transform_tangents = false;\n\t\t\t\t\tsurface_data.ensure_correct_normals = false;\n\n\t\t\t\t\tuint32_t format = mesh->surface_get_format(surface_index);\n\t\t\t\t\tERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_VERTEX));\n\t\t\t\t\tERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_BONES));\n\t\t\t\t\tERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_WEIGHTS));\n\n\t\t\t\t\tformat |= Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE;\n\t\t\t\t\tformat &= ~Mesh::ARRAY_COMPRESS_VERTEX;\n\t\t\t\t\tformat &= ~Mesh::ARRAY_COMPRESS_WEIGHTS;\n\t\t\t\t\tformat &= ~Mesh::ARRAY_FLAG_USE_16_BIT_BONES;\n\n\t\t\t\t\tArray write_arrays = mesh->surface_get_arrays(surface_index);\n\t\t\t\t\tArray read_arrays;\n\t\t\t\t\tread_arrays.resize(Mesh::ARRAY_MAX);\n\n\t\t\t\t\tread_arrays[Mesh::ARRAY_VERTEX] = write_arrays[Mesh::ARRAY_VERTEX];\n\t\t\t\t\tread_arrays[Mesh::ARRAY_BONES] = write_arrays[Mesh::ARRAY_BONES];\n\t\t\t\t\tread_arrays[Mesh::ARRAY_WEIGHTS] = write_arrays[Mesh::ARRAY_WEIGHTS];\n\n\t\t\t\t\twrite_arrays[Mesh::ARRAY_BONES] = Variant();\n\t\t\t\t\twrite_arrays[Mesh::ARRAY_WEIGHTS] = Variant();\n\n\t\t\t\t\tif (software_skinning_flags & SoftwareSkinning::FLAG_TRANSFORM_NORMALS) {\n\t\t\t\t\t\tERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_NORMAL));\n\t\t\t\t\t\tformat &= ~Mesh::ARRAY_COMPRESS_NORMAL;\n\n\t\t\t\t\t\tread_arrays[Mesh::ARRAY_NORMAL] = write_arrays[Mesh::ARRAY_NORMAL];\n\n\t\t\t\t\t\tRef mat = get_active_material(surface_index);\n\t\t\t\t\t\tif (mat.is_valid()) {\n\t\t\t\t\t\t\tRef spatial_mat = mat;\n\t\t\t\t\t\t\tif (spatial_mat.is_valid()) {\n\t\t\t\t\t\t\t\t\/\/ Spatial material, check from material settings.\n\t\t\t\t\t\t\t\tsurface_data.transform_tangents = spatial_mat->get_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING);\n\t\t\t\t\t\t\t\tsurface_data.ensure_correct_normals = spatial_mat->get_flag(SpatialMaterial::FLAG_ENSURE_CORRECT_NORMALS);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\/\/ Custom shader, must check for compiled flags.\n\t\t\t\t\t\t\t\tsurface_data.transform_tangents = VSG::storage->material_uses_tangents(mat->get_rid());\n\t\t\t\t\t\t\t\tsurface_data.ensure_correct_normals = VSG::storage->material_uses_ensure_correct_normals(mat->get_rid());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (surface_data.transform_tangents) {\n\t\t\t\t\t\t\tERR_CONTINUE(0 == (format & Mesh::ARRAY_FORMAT_TANGENT));\n\t\t\t\t\t\t\tformat &= ~Mesh::ARRAY_COMPRESS_TANGENT;\n\n\t\t\t\t\t\t\tread_arrays[Mesh::ARRAY_TANGENT] = write_arrays[Mesh::ARRAY_TANGENT];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ 1. Temporarily add surface with bone data to create the read buffer.\n\t\t\t\t\tsoftware_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, read_arrays, Array(), format);\n\n\t\t\t\t\tPoolByteArray buffer_read = visual_server->mesh_surface_get_array(mesh_rid, surface_index);\n\t\t\t\t\tsurface_data.source_buffer.append_array(buffer_read);\n\t\t\t\t\tsurface_data.source_format = software_mesh->surface_get_format(surface_index);\n\n\t\t\t\t\tsoftware_mesh->surface_remove(surface_index);\n\n\t\t\t\t\t\/\/ 2. Create the surface again without the bone data for the write buffer.\n\t\t\t\t\tsoftware_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, write_arrays, Array(), format);\n\n\t\t\t\t\tRef material = mesh->surface_get_material(surface_index);\n\t\t\t\t\tsoftware_mesh->surface_set_material(surface_index, material);\n\n\t\t\t\t\tsurface_data.buffer = visual_server->mesh_surface_get_array(mesh_rid, surface_index);\n\t\t\t\t\tsurface_data.buffer_write = surface_data.buffer.write();\n\t\t\t\t}\n\n\t\t\t\tsoftware_skinning->mesh_instance = software_mesh;\n\t\t\t\tupdate_mesh = true;\n\t\t\t}\n\n\t\t\tif (p_call_attach_skeleton) {\n\t\t\t\tvisual_server->instance_attach_skeleton(get_instance(), RID());\n\t\t\t}\n\n\t\t\tif (is_visible_in_tree() && (software_skinning_flags & SoftwareSkinning::FLAG_BONES_READY)) {\n\t\t\t\t\/\/ Initialize from current skeleton pose.\n\t\t\t\t_update_skinning();\n\t\t\t}\n\t\t} else {\n\t\t\tERR_FAIL_COND(!skin_ref->get_skeleton_node());\n\t\t\tif (skin_ref->get_skeleton_node()->is_connected(\"skeleton_updated\", this, \"_update_skinning\")) {\n\t\t\t\tskin_ref->get_skeleton_node()->disconnect(\"skeleton_updated\", this, \"_update_skinning\");\n\t\t\t}\n\n\t\t\tif (p_call_attach_skeleton) {\n\t\t\t\tvisual_server->instance_attach_skeleton(get_instance(), skin_ref->get_skeleton());\n\t\t\t}\n\n\t\t\tif (software_skinning) {\n\t\t\t\tmemdelete(software_skinning);\n\t\t\t\tsoftware_skinning = nullptr;\n\t\t\t\tupdate_mesh = true;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (p_call_attach_skeleton) {\n\t\t\tvisual_server->instance_attach_skeleton(get_instance(), RID());\n\t\t}\n\t\tif (software_skinning) {\n\t\t\tmemdelete(software_skinning);\n\t\t\tsoftware_skinning = nullptr;\n\t\t\tupdate_mesh = true;\n\t\t}\n\t}\n\n\tRID render_mesh = software_skinning ? software_skinning->mesh_instance->get_rid() : mesh->get_rid();\n\tif (update_mesh || (render_mesh != get_base())) {\n\t\tset_base(render_mesh);\n\n\t\t\/\/ Update instance materials after switching mesh.\n\t\tint surface_count = mesh->get_surface_count();\n\t\tfor (int surface_index = 0; surface_index < surface_count; ++surface_index) {\n\t\t\tif (materials[surface_index].is_valid()) {\n\t\t\t\tvisual_server->instance_set_surface_material(get_instance(), surface_index, materials[surface_index]->get_rid());\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid MeshInstance::_update_skinning() {\n\tERR_FAIL_COND(!_is_software_skinning_enabled());\n#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED)\n\tERR_FAIL_COND(!is_visible_in_tree());\n#else\n\tERR_FAIL_COND(!is_visible());\n#endif\n\n\tERR_FAIL_COND(!software_skinning);\n\tRef software_skinning_mesh = software_skinning->mesh_instance;\n\tERR_FAIL_COND(!software_skinning_mesh.is_valid());\n\tRID mesh_rid = software_skinning_mesh->get_rid();\n\tERR_FAIL_COND(!mesh_rid.is_valid());\n\n\tERR_FAIL_COND(!mesh.is_valid());\n\tRID source_mesh_rid = mesh->get_rid();\n\tERR_FAIL_COND(!source_mesh_rid.is_valid());\n\n\tERR_FAIL_COND(skin_ref.is_null());\n\tRID skeleton = skin_ref->get_skeleton();\n\tERR_FAIL_COND(!skeleton.is_valid());\n\n\tVector3 aabb_min = Vector3(FLT_MAX, FLT_MAX, FLT_MAX);\n\tVector3 aabb_max = Vector3(-FLT_MAX, -FLT_MAX, -FLT_MAX);\n\n\tVisualServer *visual_server = VisualServer::get_singleton();\n\n\t\/\/ Prepare bone transforms.\n\tconst int num_bones = visual_server->skeleton_get_bone_count(skeleton);\n\tERR_FAIL_COND(num_bones <= 0);\n\tTransform *bone_transforms = (Transform *)alloca(sizeof(Transform) * num_bones);\n\tfor (int bone_index = 0; bone_index < num_bones; ++bone_index) {\n\t\tbone_transforms[bone_index] = visual_server->skeleton_bone_get_transform(skeleton, bone_index);\n\t}\n\n\t\/\/ Apply skinning.\n\tint surface_count = software_skinning_mesh->get_surface_count();\n\tfor (int surface_index = 0; surface_index < surface_count; ++surface_index) {\n\t\tERR_CONTINUE((uint32_t)surface_index >= software_skinning->surface_data.size());\n\t\tconst SoftwareSkinning::SurfaceData &surface_data = software_skinning->surface_data[surface_index];\n\t\tconst bool transform_tangents = surface_data.transform_tangents;\n\t\tconst bool ensure_correct_normals = surface_data.ensure_correct_normals;\n\n\t\tconst uint32_t format_write = software_skinning_mesh->surface_get_format(surface_index);\n\n\t\tconst int vertex_count_write = software_skinning_mesh->surface_get_array_len(surface_index);\n\t\tconst int index_count_write = software_skinning_mesh->surface_get_array_index_len(surface_index);\n\n\t\tuint32_t array_offsets_write[Mesh::ARRAY_MAX];\n\t\tuint32_t array_strides_write[Mesh::ARRAY_MAX];\n\t\tvisual_server->mesh_surface_make_offsets_from_format(format_write, vertex_count_write, index_count_write, array_offsets_write, array_strides_write);\n\t\tERR_FAIL_COND(array_strides_write[Mesh::ARRAY_VERTEX] != array_strides_write[Mesh::ARRAY_NORMAL]);\n\t\tconst uint32_t stride_write = array_strides_write[Mesh::ARRAY_VERTEX];\n\t\tconst uint32_t offset_vertices_write = array_offsets_write[Mesh::ARRAY_VERTEX];\n\t\tconst uint32_t offset_normals_write = array_offsets_write[Mesh::ARRAY_NORMAL];\n\t\tconst uint32_t offset_tangents_write = array_offsets_write[Mesh::ARRAY_TANGENT];\n\n\t\tPoolByteArray buffer_source = surface_data.source_buffer;\n\t\tPoolByteArray::Read buffer_read = buffer_source.read();\n\n\t\tconst uint32_t format_read = surface_data.source_format;\n\n\t\tERR_CONTINUE(0 == (format_read & Mesh::ARRAY_FORMAT_BONES));\n\t\tERR_CONTINUE(0 == (format_read & Mesh::ARRAY_FORMAT_WEIGHTS));\n\n\t\tconst int vertex_count = mesh->surface_get_array_len(surface_index);\n\t\tconst int index_count = mesh->surface_get_array_index_len(surface_index);\n\n\t\tERR_CONTINUE(vertex_count != vertex_count_write);\n\n\t\tuint32_t array_offsets[Mesh::ARRAY_MAX];\n\t\tuint32_t array_strides[Mesh::ARRAY_MAX];\n\t\tvisual_server->mesh_surface_make_offsets_from_format(format_read, vertex_count, index_count, array_offsets, array_strides);\n\t\tERR_FAIL_COND(array_strides[Mesh::ARRAY_VERTEX] != array_strides[Mesh::ARRAY_NORMAL]);\n\t\tconst uint32_t stride = array_strides[Mesh::ARRAY_VERTEX];\n\t\tconst uint32_t offset_vertices = array_offsets[Mesh::ARRAY_VERTEX];\n\t\tconst uint32_t offset_normals = array_offsets[Mesh::ARRAY_NORMAL];\n\t\tconst uint32_t offset_tangents = array_offsets[Mesh::ARRAY_TANGENT];\n\t\tconst uint32_t offset_bones = array_offsets[Mesh::ARRAY_BONES];\n\t\tconst uint32_t offset_weights = array_offsets[Mesh::ARRAY_WEIGHTS];\n\n\t\tPoolByteArray buffer = surface_data.buffer;\n\t\tPoolByteArray::Write buffer_write = surface_data.buffer_write;\n\n\t\tfor (int vertex_index = 0; vertex_index < vertex_count; ++vertex_index) {\n\t\t\tconst uint32_t vertex_offset = vertex_index * stride;\n\t\t\tconst uint32_t vertex_offset_write = vertex_index * stride_write;\n\n\t\t\tfloat bone_weights[4];\n\t\t\tconst float *weight_ptr = (const float *)(buffer_read.ptr() + offset_weights + vertex_offset);\n\t\t\tbone_weights[0] = weight_ptr[0];\n\t\t\tbone_weights[1] = weight_ptr[1];\n\t\t\tbone_weights[2] = weight_ptr[2];\n\t\t\tbone_weights[3] = weight_ptr[3];\n\n\t\t\tconst uint8_t *bones_ptr = buffer_read.ptr() + offset_bones + vertex_offset;\n\t\t\tconst int b0 = bones_ptr[0];\n\t\t\tconst int b1 = bones_ptr[1];\n\t\t\tconst int b2 = bones_ptr[2];\n\t\t\tconst int b3 = bones_ptr[3];\n\n\t\t\tTransform transform;\n\t\t\ttransform.origin =\n\t\t\t\t\tbone_weights[0] * bone_transforms[b0].origin +\n\t\t\t\t\tbone_weights[1] * bone_transforms[b1].origin +\n\t\t\t\t\tbone_weights[2] * bone_transforms[b2].origin +\n\t\t\t\t\tbone_weights[3] * bone_transforms[b3].origin;\n\n\t\t\ttransform.basis =\n\t\t\t\t\tbone_transforms[b0].basis * bone_weights[0] +\n\t\t\t\t\tbone_transforms[b1].basis * bone_weights[1] +\n\t\t\t\t\tbone_transforms[b2].basis * bone_weights[2] +\n\t\t\t\t\tbone_transforms[b3].basis * bone_weights[3];\n\n\t\t\tconst Vector3 &vertex_read = (const Vector3 &)buffer_read[vertex_offset + offset_vertices];\n\t\t\tVector3 &vertex = (Vector3 &)buffer_write[vertex_offset_write + offset_vertices_write];\n\t\t\tvertex = transform.xform(vertex_read);\n\n\t\t\tif (software_skinning_flags & SoftwareSkinning::FLAG_TRANSFORM_NORMALS) {\n\t\t\t\tif (ensure_correct_normals) {\n\t\t\t\t\ttransform.basis.invert();\n\t\t\t\t\ttransform.basis.transpose();\n\t\t\t\t}\n\n\t\t\t\tconst Vector3 &normal_read = (const Vector3 &)buffer_read[vertex_offset + offset_normals];\n\t\t\t\tVector3 &normal = (Vector3 &)buffer_write[vertex_offset_write + offset_normals_write];\n\t\t\t\tnormal = transform.basis.xform(normal_read);\n\n\t\t\t\tif (transform_tangents) {\n\t\t\t\t\tconst Vector3 &tangent_read = (const Vector3 &)buffer_read[vertex_offset + offset_tangents];\n\t\t\t\t\tVector3 &tangent = (Vector3 &)buffer_write[vertex_offset_write + offset_tangents_write];\n\t\t\t\t\ttangent = transform.basis.xform(tangent_read);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\taabb_min.x = MIN(aabb_min.x, vertex.x);\n\t\t\taabb_min.y = MIN(aabb_min.y, vertex.y);\n\t\t\taabb_min.z = MIN(aabb_min.z, vertex.z);\n\t\t\taabb_max.x = MAX(aabb_max.x, vertex.x);\n\t\t\taabb_max.y = MAX(aabb_max.y, vertex.y);\n\t\t\taabb_max.z = MAX(aabb_max.z, vertex.z);\n\t\t}\n\n\t\tvisual_server->mesh_surface_update_region(mesh_rid, surface_index, 0, buffer);\n\t}\n\n\tvisual_server->mesh_set_custom_aabb(mesh_rid, AABB(aabb_min, aabb_max - aabb_min));\n\n\tsoftware_skinning_flags |= SoftwareSkinning::FLAG_BONES_READY;\n}\n\nvoid MeshInstance::set_skin(const Ref &p_skin) {\n\tskin_internal = p_skin;\n\tskin = p_skin;\n\tif (!is_inside_tree()) {\n\t\treturn;\n\t}\n\t_resolve_skeleton_path();\n}\n\nRef MeshInstance::get_skin() const {\n\treturn skin;\n}\n\nvoid MeshInstance::set_skeleton_path(const NodePath &p_skeleton) {\n\tskeleton_path = p_skeleton;\n\tif (!is_inside_tree()) {\n\t\treturn;\n\t}\n\t_resolve_skeleton_path();\n}\n\nNodePath MeshInstance::get_skeleton_path() {\n\treturn skeleton_path;\n}\n\nAABB MeshInstance::get_aabb() const {\n\tif (!mesh.is_null()) {\n\t\treturn mesh->get_aabb();\n\t}\n\n\treturn AABB();\n}\n\nPoolVector MeshInstance::get_faces(uint32_t p_usage_flags) const {\n\tif (!(p_usage_flags & (FACES_SOLID | FACES_ENCLOSING))) {\n\t\treturn PoolVector();\n\t}\n\n\tif (mesh.is_null()) {\n\t\treturn PoolVector();\n\t}\n\n\treturn mesh->get_faces();\n}\n\nNode *MeshInstance::create_trimesh_collision_node() {\n\tif (mesh.is_null()) {\n\t\treturn nullptr;\n\t}\n\n\tRef shape = mesh->create_trimesh_shape();\n\tif (shape.is_null()) {\n\t\treturn nullptr;\n\t}\n\n\tStaticBody *static_body = memnew(StaticBody);\n\tCollisionShape *cshape = memnew(CollisionShape);\n\tcshape->set_shape(shape);\n\tstatic_body->add_child(cshape);\n\treturn static_body;\n}\n\nvoid MeshInstance::create_trimesh_collision() {\n\tStaticBody *static_body = Object::cast_to(create_trimesh_collision_node());\n\tERR_FAIL_COND(!static_body);\n\tstatic_body->set_name(String(get_name()) + \"_col\");\n\n\tadd_child(static_body);\n\tif (get_owner()) {\n\t\tCollisionShape *cshape = Object::cast_to(static_body->get_child(0));\n\t\tstatic_body->set_owner(get_owner());\n\t\tcshape->set_owner(get_owner());\n\t}\n}\n\nNode *MeshInstance::create_multiple_convex_collisions_node() {\n\tif (mesh.is_null()) {\n\t\treturn nullptr;\n\t}\n\n\tVector> shapes = mesh->convex_decompose();\n\tif (!shapes.size()) {\n\t\treturn nullptr;\n\t}\n\n\tStaticBody *static_body = memnew(StaticBody);\n\tfor (int i = 0; i < shapes.size(); i++) {\n\t\tCollisionShape *cshape = memnew(CollisionShape);\n\t\tcshape->set_shape(shapes[i]);\n\t\tstatic_body->add_child(cshape);\n\t}\n\treturn static_body;\n}\n\nvoid MeshInstance::create_multiple_convex_collisions() {\n\tStaticBody *static_body = Object::cast_to(create_multiple_convex_collisions_node());\n\tERR_FAIL_COND(!static_body);\n\tstatic_body->set_name(String(get_name()) + \"_col\");\n\n\tadd_child(static_body);\n\tif (get_owner()) {\n\t\tstatic_body->set_owner(get_owner());\n\t\tint count = static_body->get_child_count();\n\t\tfor (int i = 0; i < count; i++) {\n\t\t\tCollisionShape *cshape = Object::cast_to(static_body->get_child(i));\n\t\t\tcshape->set_owner(get_owner());\n\t\t}\n\t}\n}\n\nNode *MeshInstance::create_convex_collision_node(bool p_clean, bool p_simplify) {\n\tif (mesh.is_null()) {\n\t\treturn nullptr;\n\t}\n\n\tRef shape = mesh->create_convex_shape(p_clean, p_simplify);\n\tif (shape.is_null()) {\n\t\treturn nullptr;\n\t}\n\n\tStaticBody *static_body = memnew(StaticBody);\n\tCollisionShape *cshape = memnew(CollisionShape);\n\tcshape->set_shape(shape);\n\tstatic_body->add_child(cshape);\n\treturn static_body;\n}\n\nvoid MeshInstance::create_convex_collision(bool p_clean, bool p_simplify) {\n\tStaticBody *static_body = Object::cast_to(create_convex_collision_node(p_clean, p_simplify));\n\tERR_FAIL_COND(!static_body);\n\tstatic_body->set_name(String(get_name()) + \"_col\");\n\n\tadd_child(static_body);\n\tif (get_owner()) {\n\t\tCollisionShape *cshape = Object::cast_to(static_body->get_child(0));\n\t\tstatic_body->set_owner(get_owner());\n\t\tcshape->set_owner(get_owner());\n\t}\n}\n\nvoid MeshInstance::_notification(int p_what) {\n\tif (p_what == NOTIFICATION_ENTER_TREE) {\n\t\t_resolve_skeleton_path();\n\t}\n\n\tif (p_what == NOTIFICATION_VISIBILITY_CHANGED) {\n\t\tif (skin_ref.is_valid() && mesh.is_valid() && _is_software_skinning_enabled()) {\n\t\t\tERR_FAIL_COND(!skin_ref->get_skeleton_node());\n\t\t\tif (is_visible_in_tree()) {\n\t\t\t\tskin_ref->get_skeleton_node()->connect(\"skeleton_updated\", this, \"_update_skinning\");\n\t\t\t} else {\n\t\t\t\tskin_ref->get_skeleton_node()->disconnect(\"skeleton_updated\", this, \"_update_skinning\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nint MeshInstance::get_surface_material_count() const {\n\treturn materials.size();\n}\n\nvoid MeshInstance::set_surface_material(int p_surface, const Ref &p_material) {\n\tERR_FAIL_INDEX(p_surface, materials.size());\n\n\tmaterials.write[p_surface] = p_material;\n\n\tif (materials[p_surface].is_valid()) {\n\t\tVS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, materials[p_surface]->get_rid());\n\t} else {\n\t\tVS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, RID());\n\t}\n\n\tif (software_skinning) {\n\t\t_initialize_skinning(true);\n\t}\n}\n\nRef MeshInstance::get_surface_material(int p_surface) const {\n\tERR_FAIL_INDEX_V(p_surface, materials.size(), Ref());\n\n\treturn materials[p_surface];\n}\n\nRef MeshInstance::get_active_material(int p_surface) const {\n\tRef material_override = get_material_override();\n\tif (material_override.is_valid()) {\n\t\treturn material_override;\n\t}\n\n\tRef surface_material = get_surface_material(p_surface);\n\tif (surface_material.is_valid()) {\n\t\treturn surface_material;\n\t}\n\n\tRef mesh = get_mesh();\n\tif (mesh.is_valid()) {\n\t\treturn mesh->surface_get_material(p_surface);\n\t}\n\n\treturn Ref();\n}\n\nvoid MeshInstance::set_material_override(const Ref &p_material) {\n\tif (p_material == get_material_override()) {\n\t\treturn;\n\t}\n\n\tGeometryInstance::set_material_override(p_material);\n\n\tif (software_skinning) {\n\t\t_initialize_skinning(true);\n\t}\n}\n\nvoid MeshInstance::set_material_overlay(const Ref &p_material) {\n\tif (p_material == get_material_overlay()) {\n\t\treturn;\n\t}\n\n\tGeometryInstance::set_material_overlay(p_material);\n}\n\nvoid MeshInstance::set_software_skinning_transform_normals(bool p_enabled) {\n\tif (p_enabled == is_software_skinning_transform_normals_enabled()) {\n\t\treturn;\n\t}\n\n\tif (p_enabled) {\n\t\tsoftware_skinning_flags |= SoftwareSkinning::FLAG_TRANSFORM_NORMALS;\n\t} else {\n\t\tsoftware_skinning_flags &= ~SoftwareSkinning::FLAG_TRANSFORM_NORMALS;\n\t}\n\n\tif (software_skinning) {\n\t\t_initialize_skinning(true);\n\t}\n}\n\nbool MeshInstance::is_software_skinning_transform_normals_enabled() const {\n\treturn 0 != (software_skinning_flags & SoftwareSkinning::FLAG_TRANSFORM_NORMALS);\n}\n\nvoid MeshInstance::_mesh_changed() {\n\tERR_FAIL_COND(mesh.is_null());\n\tmaterials.resize(mesh->get_surface_count());\n\n\tif (software_skinning) {\n\t\t_initialize_skinning(true);\n\t}\n}\n\nvoid MeshInstance::create_debug_tangents() {\n\tVector lines;\n\tVector colors;\n\n\tRef mesh = get_mesh();\n\tif (!mesh.is_valid()) {\n\t\treturn;\n\t}\n\n\tfor (int i = 0; i < mesh->get_surface_count(); i++) {\n\t\tArray arrays = mesh->surface_get_arrays(i);\n\t\tVector verts = arrays[Mesh::ARRAY_VERTEX];\n\t\tVector norms = arrays[Mesh::ARRAY_NORMAL];\n\t\tif (norms.size() == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tVector tangents = arrays[Mesh::ARRAY_TANGENT];\n\t\tif (tangents.size() == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (int j = 0; j < verts.size(); j++) {\n\t\t\tVector3 v = verts[j];\n\t\t\tVector3 n = norms[j];\n\t\t\tVector3 t = Vector3(tangents[j * 4 + 0], tangents[j * 4 + 1], tangents[j * 4 + 2]);\n\t\t\tVector3 b = (n.cross(t)).normalized() * tangents[j * 4 + 3];\n\n\t\t\tlines.push_back(v); \/\/normal\n\t\t\tcolors.push_back(Color(0, 0, 1)); \/\/color\n\t\t\tlines.push_back(v + n * 0.04); \/\/normal\n\t\t\tcolors.push_back(Color(0, 0, 1)); \/\/color\n\n\t\t\tlines.push_back(v); \/\/tangent\n\t\t\tcolors.push_back(Color(1, 0, 0)); \/\/color\n\t\t\tlines.push_back(v + t * 0.04); \/\/tangent\n\t\t\tcolors.push_back(Color(1, 0, 0)); \/\/color\n\n\t\t\tlines.push_back(v); \/\/binormal\n\t\t\tcolors.push_back(Color(0, 1, 0)); \/\/color\n\t\t\tlines.push_back(v + b * 0.04); \/\/binormal\n\t\t\tcolors.push_back(Color(0, 1, 0)); \/\/color\n\t\t}\n\t}\n\n\tif (lines.size()) {\n\t\tRef sm;\n\t\tsm.instance();\n\n\t\tsm->set_flag(SpatialMaterial::FLAG_UNSHADED, true);\n\t\tsm->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);\n\t\tsm->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);\n\n\t\tRef am;\n\t\tam.instance();\n\t\tArray a;\n\t\ta.resize(Mesh::ARRAY_MAX);\n\t\ta[Mesh::ARRAY_VERTEX] = lines;\n\t\ta[Mesh::ARRAY_COLOR] = colors;\n\n\t\tam->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, a);\n\t\tam->surface_set_material(0, sm);\n\n\t\tMeshInstance *mi = memnew(MeshInstance);\n\t\tmi->set_mesh(am);\n\t\tmi->set_name(\"DebugTangents\");\n\t\tadd_child(mi);\n#ifdef TOOLS_ENABLED\n\n\t\tif (is_inside_tree() && this == get_tree()->get_edited_scene_root()) {\n\t\t\tmi->set_owner(this);\n\t\t} else {\n\t\t\tmi->set_owner(get_owner());\n\t\t}\n#endif\n\t}\n}\n\nbool MeshInstance::is_mergeable_with(Node *p_other) const {\n\tconst MeshInstance *mi = Object::cast_to(p_other);\n\n\tif (mi) {\n\t\treturn _is_mergeable_with(*mi);\n\t}\n\n\treturn false;\n}\n\nbool MeshInstance::_is_mergeable_with(const MeshInstance &p_other) const {\n\tif (!get_mesh().is_valid() || !p_other.get_mesh().is_valid()) {\n\t\treturn false;\n\t}\n\tif (!get_allow_merging() || !p_other.get_allow_merging()) {\n\t\treturn false;\n\t}\n\n\t\/\/ various settings that must match\n\tif (get_material_overlay() != p_other.get_material_overlay()) {\n\t\treturn false;\n\t}\n\tif (get_material_override() != p_other.get_material_override()) {\n\t\treturn false;\n\t}\n\tif (get_cast_shadows_setting() != p_other.get_cast_shadows_setting()) {\n\t\treturn false;\n\t}\n\tif (get_flag(FLAG_USE_BAKED_LIGHT) != p_other.get_flag(FLAG_USE_BAKED_LIGHT)) {\n\t\treturn false;\n\t}\n\tif (is_visible() != p_other.is_visible()) {\n\t\treturn false;\n\t}\n\n\tRef rmesh_a = get_mesh();\n\tRef rmesh_b = p_other.get_mesh();\n\n\tint num_surfaces = rmesh_a->get_surface_count();\n\tif (num_surfaces != rmesh_b->get_surface_count()) {\n\t\treturn false;\n\t}\n\n\tfor (int n = 0; n < num_surfaces; n++) {\n\t\t\/\/ materials must match\n\t\tif (get_active_material(n) != p_other.get_active_material(n)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ formats must match\n\t\tuint32_t format_a = rmesh_a->surface_get_format(n);\n\t\tuint32_t format_b = rmesh_b->surface_get_format(n);\n\n\t\tif (format_a != format_b) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ NOTE : These three commented out sections below are more conservative\n\t\/\/ checks for whether to allow mesh merging. I am not absolutely sure a priori\n\t\/\/ how conservative we need to be, so we can further enable this if testing\n\t\/\/ shows they are required.\n\n\t\/\/\tif (get_surface_material_count() != p_other.get_surface_material_count()) {\n\t\/\/\t\treturn false;\n\t\/\/\t}\n\n\t\/\/\tfor (int n = 0; n < get_surface_material_count(); n++) {\n\t\/\/\t\tif (get_surface_material(n) != p_other.get_surface_material(n)) {\n\t\/\/\t\t\treturn false;\n\t\/\/\t\t}\n\t\/\/\t}\n\n\t\/\/ test only allow identical meshes\n\t\/\/\tif (get_mesh() != p_other.get_mesh()) {\n\t\/\/\t\treturn false;\n\t\/\/\t}\n\n\treturn true;\n}\n\nvoid MeshInstance::_merge_into_mesh_data(const MeshInstance &p_mi, const Transform &p_dest_tr_inv, int p_surface_id, PoolVector &r_verts, PoolVector &r_norms, PoolVector &r_tangents, PoolVector &r_colors, PoolVector &r_uvs, PoolVector &r_uv2s, PoolVector &r_inds) {\n\t_merge_log(\"\\t\\t\\tmesh data from \" + p_mi.get_name());\n\n\t\/\/ get the mesh verts in local space\n\tRef rmesh = p_mi.get_mesh();\n\n\tif (rmesh->get_surface_count() <= p_surface_id) {\n\t\treturn;\n\t}\n\n\tArray arrays = rmesh->surface_get_arrays(p_surface_id);\n\n\tPoolVector verts = arrays[VS::ARRAY_VERTEX];\n\tPoolVector normals = arrays[VS::ARRAY_NORMAL];\n\tPoolVector tangents = arrays[VS::ARRAY_TANGENT];\n\tPoolVector colors = arrays[VS::ARRAY_COLOR];\n\tPoolVector uvs = arrays[VS::ARRAY_TEX_UV];\n\tPoolVector uv2s = arrays[VS::ARRAY_TEX_UV2];\n\tPoolVector indices = arrays[VS::ARRAY_INDEX];\n\n\t\/\/ The attributes present must match the first mesh for the attributes\n\t\/\/ to remain in sync. Here we reject meshes with different attributes.\n\t\/\/ We could alternatively invent missing attributes.\n\t\/\/ This should hopefully be already caught by the mesh_format, but is included just in case here.\n\n\t\/\/ Don't perform these checks on the first Mesh, the first Mesh is a master\n\t\/\/ and determines the attributes we want to be present.\n\tif (r_verts.size() != 0) {\n\t\tif ((bool)r_norms.size() != (bool)normals.size()) {\n\t\t\tERR_FAIL_MSG(\"Attribute mismatch with first Mesh (Normals), ignoring surface.\");\n\t\t}\n\t\tif ((bool)r_tangents.size() != (bool)tangents.size()) {\n\t\t\tERR_FAIL_MSG(\"Attribute mismatch with first Mesh (Tangents), ignoring surface.\");\n\t\t}\n\t\tif ((bool)r_colors.size() != (bool)colors.size()) {\n\t\t\tERR_FAIL_MSG(\"Attribute mismatch with first Mesh (Colors), ignoring surface.\");\n\t\t}\n\t\tif ((bool)r_uvs.size() != (bool)uvs.size()) {\n\t\t\tERR_FAIL_MSG(\"Attribute mismatch with first Mesh (UVs), ignoring surface.\");\n\t\t}\n\t\tif ((bool)r_uv2s.size() != (bool)uv2s.size()) {\n\t\t\tERR_FAIL_MSG(\"Attribute mismatch with first Mesh (UV2s), ignoring surface.\");\n\t\t}\n\t}\n\n\t\/\/ The checking for valid triangles should be on WORLD SPACE vertices,\n\t\/\/ NOT model space\n\n\t\/\/ special case, if no indices, create some\n\tint num_indices_before = indices.size();\n\tif (!_ensure_indices_valid(indices, verts)) {\n\t\t_merge_log(\"\\tignoring INVALID TRIANGLES (duplicate indices or zero area triangle) detected in \" + p_mi.get_name() + \", num inds before \/ after \" + itos(num_indices_before) + \" \/ \" + itos(indices.size()));\n\t}\n\n\t\/\/ the first index of this mesh is offset from the verts we already have stored in the merged mesh\n\tint first_index = r_verts.size();\n\n\t\/\/ transform verts to world space\n\tTransform tr = p_mi.get_global_transform();\n\n\t\/\/ But relative to the destination transform.\n\t\/\/ This can either be identity (when the destination is global space),\n\t\/\/ or the global transform of the owner MeshInstance (if using local space is selected).\n\ttr = p_dest_tr_inv * tr;\n\n\t\/\/ to transform normals\n\tBasis normal_basis = tr.basis.inverse();\n\tnormal_basis.transpose();\n\n\tfor (int n = 0; n < verts.size(); n++) {\n\t\tVector3 pt_world = tr.xform(verts[n]);\n\t\tr_verts.push_back(pt_world);\n\n\t\tif (normals.size()) {\n\t\t\tVector3 pt_norm = normal_basis.xform(normals[n]);\n\t\t\tpt_norm.normalize();\n\t\t\tr_norms.push_back(pt_norm);\n\t\t}\n\n\t\tif (tangents.size()) {\n\t\t\tint tstart = n * 4;\n\t\t\tVector3 pt_tangent = Vector3(tangents[tstart], tangents[tstart + 1], tangents[tstart + 2]);\n\t\t\treal_t fourth = tangents[tstart + 3];\n\n\t\t\tpt_tangent = normal_basis.xform(pt_tangent);\n\t\t\tpt_tangent.normalize();\n\t\t\tr_tangents.push_back(pt_tangent.x);\n\t\t\tr_tangents.push_back(pt_tangent.y);\n\t\t\tr_tangents.push_back(pt_tangent.z);\n\t\t\tr_tangents.push_back(fourth);\n\t\t}\n\n\t\tif (colors.size()) {\n\t\t\tr_colors.push_back(colors[n]);\n\t\t}\n\n\t\tif (uvs.size()) {\n\t\t\tr_uvs.push_back(uvs[n]);\n\t\t}\n\n\t\tif (uv2s.size()) {\n\t\t\tr_uv2s.push_back(uv2s[n]);\n\t\t}\n\t}\n\n\t\/\/ indices\n\tfor (int n = 0; n < indices.size(); n++) {\n\t\tint ind = indices[n] + first_index;\n\t\tr_inds.push_back(ind);\n\t}\n}\n\nbool MeshInstance::_ensure_indices_valid(PoolVector &r_indices, const PoolVector &p_verts) const {\n\t\/\/ no indices? create some\n\tif (!r_indices.size()) {\n\t\t_merge_log(\"\\t\\t\\t\\tindices are blank, creating...\");\n\n\t\t\/\/ indices are blank!! let's create some, assuming the mesh is using triangles\n\t\tr_indices.resize(p_verts.size());\n\t\tPoolVector::Write write = r_indices.write();\n\t\tint *pi = write.ptr();\n\n\t\t\/\/ this is assuming each triangle vertex is unique\n\t\tfor (int n = 0; n < p_verts.size(); n++) {\n\t\t\t*pi = n;\n\t\t\tpi++;\n\t\t}\n\t}\n\n\tif (!_check_for_valid_indices(r_indices, p_verts, nullptr)) {\n\t\tLocalVector new_inds;\n\t\t_check_for_valid_indices(r_indices, p_verts, &new_inds);\n\n\t\t\/\/ copy the new indices\n\t\tr_indices.resize(new_inds.size());\n\t\tPoolVector::Write write = r_indices.write();\n\t\tint *pi = write.ptr();\n\n\t\tfor (int n = 0; n < new_inds.size(); n++) {\n\t\t\tpi[n] = new_inds[n];\n\t\t}\n\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\/\/ check for invalid tris, or make a list of the valid triangles, depending on whether r_inds is set\nbool MeshInstance::_check_for_valid_indices(const PoolVector &p_inds, const PoolVector &p_verts, LocalVector *r_inds) const {\n\tint nTris = p_inds.size();\n\tnTris \/= 3;\n\tint indCount = 0;\n\n\tfor (int t = 0; t < nTris; t++) {\n\t\tint i0 = p_inds[indCount++];\n\t\tint i1 = p_inds[indCount++];\n\t\tint i2 = p_inds[indCount++];\n\n\t\tbool ok = true;\n\n\t\t\/\/ if the indices are the same, the triangle is invalid\n\t\tif (i0 == i1) {\n\t\t\tok = false;\n\t\t}\n\t\tif (i1 == i2) {\n\t\t\tok = false;\n\t\t}\n\t\tif (i0 == i2) {\n\t\t\tok = false;\n\t\t}\n\n\t\t\/\/ check positions\n\t\tif (ok) {\n\t\t\t\/\/ vertex positions\n\t\t\tconst Vector3 &p0 = p_verts[i0];\n\t\t\tconst Vector3 &p1 = p_verts[i1];\n\t\t\tconst Vector3 &p2 = p_verts[i2];\n\n\t\t\t\/\/ if the area is zero, the triangle is invalid (and will crash xatlas if we use it)\n\t\t\tif (_triangle_is_degenerate(p0, p1, p2, 0.00001)) {\n\t\t\t\t_merge_log(\"\\t\\tdetected zero area triangle, ignoring\");\n\t\t\t\tok = false;\n\t\t\t}\n\t\t}\n\n\t\tif (ok) {\n\t\t\t\/\/ if the triangle is ok, we will output it if we are outputting\n\t\t\tif (r_inds) {\n\t\t\t\tr_inds->push_back(i0);\n\t\t\t\tr_inds->push_back(i1);\n\t\t\t\tr_inds->push_back(i2);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ if triangle not ok, return failed check if we are not outputting\n\t\t\tif (!r_inds) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool MeshInstance::_triangle_is_degenerate(const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_c, real_t p_epsilon) const {\n\t\/\/ not interested in the actual area, but numerical stability\n\tVector3 edge1 = p_b - p_a;\n\tVector3 edge2 = p_c - p_a;\n\n\t\/\/ for numerical stability keep these values reasonably high\n\tedge1 *= 1024.0;\n\tedge2 *= 1024.0;\n\n\tVector3 vec = edge1.cross(edge2);\n\treal_t sl = vec.length_squared();\n\n\tif (sl <= p_epsilon) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\/\/ If p_check_compatibility is set to false you MUST have performed a prior check using\n\/\/ is_mergeable_with, otherwise you could get mismatching surface formats leading to graphical errors etc.\nbool MeshInstance::merge_meshes(Vector p_list, bool p_use_global_space, bool p_check_compatibility) {\n\tif (p_list.size() < 1) {\n\t\t\/\/ should not happen but just in case\n\t\treturn false;\n\t}\n\n\t\/\/ use the first mesh instance to get common data like number of surfaces\n\tconst MeshInstance *first = p_list[0];\n\n\t\/\/ Mesh compatibility checking. This is relatively expensive, so if done already (e.g. in Room system)\n\t\/\/ this step can be avoided.\n\tLocalVector compat_list;\n\tif (p_check_compatibility) {\n\t\tcompat_list.resize(p_list.size());\n\n\t\tfor (int n = 0; n < p_list.size(); n++) {\n\t\t\tcompat_list[n] = false;\n\t\t}\n\n\t\tcompat_list[0] = true;\n\n\t\tfor (uint32_t n = 1; n < compat_list.size(); n++) {\n\t\t\tcompat_list[n] = first->_is_mergeable_with(*p_list[n]);\n\n\t\t\tif (compat_list[n] == false) {\n\t\t\t\tWARN_PRINT(\"MeshInstance \" + p_list[n]->get_name() + \" is incompatible for merging with \" + first->get_name() + \", ignoring.\");\n\t\t\t}\n\t\t}\n\t}\n\n\tRef am;\n\tam.instance();\n\n\t\/\/ If we want a local space result, we need the world space transform of this MeshInstance\n\t\/\/ available to back transform verts from world space.\n\tTransform dest_tr_inv;\n\tif (!p_use_global_space) {\n\t\tif (is_inside_tree()) {\n\t\t\tdest_tr_inv = get_global_transform();\n\t\t\tdest_tr_inv.affine_invert();\n\t\t} else {\n\t\t\tWARN_PRINT(\"MeshInstance must be inside tree to merge using local space, falling back to global space.\");\n\t\t}\n\t}\n\n\tfor (int s = 0; s < first->get_mesh()->get_surface_count(); s++) {\n\t\tPoolVector verts;\n\t\tPoolVector normals;\n\t\tPoolVector tangents;\n\t\tPoolVector colors;\n\t\tPoolVector uvs;\n\t\tPoolVector uv2s;\n\t\tPoolVector inds;\n\n\t\tfor (int n = 0; n < p_list.size(); n++) {\n\t\t\t\/\/ Ignore if the mesh is incompatible\n\t\t\tif (p_check_compatibility && (!compat_list[n])) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t_merge_into_mesh_data(*p_list[n], dest_tr_inv, s, verts, normals, tangents, colors, uvs, uv2s, inds);\n\t\t} \/\/ for n through source meshes\n\n\t\tif (!verts.size()) {\n\t\t\tWARN_PRINT_ONCE(\"No vertices for surface\");\n\t\t}\n\n\t\t\/\/ sanity check on the indices\n\t\tfor (int n = 0; n < inds.size(); n++) {\n\t\t\tint i = inds[n];\n\t\t\tif (i >= verts.size()) {\n\t\t\t\tWARN_PRINT_ONCE(\"Mesh index out of range, invalid mesh, aborting\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tArray arr;\n\t\tarr.resize(Mesh::ARRAY_MAX);\n\t\tarr[Mesh::ARRAY_VERTEX] = verts;\n\t\tif (normals.size()) {\n\t\t\tarr[Mesh::ARRAY_NORMAL] = normals;\n\t\t}\n\t\tif (tangents.size()) {\n\t\t\tarr[Mesh::ARRAY_TANGENT] = tangents;\n\t\t}\n\t\tif (colors.size()) {\n\t\t\tarr[Mesh::ARRAY_COLOR] = colors;\n\t\t}\n\t\tif (uvs.size()) {\n\t\t\tarr[Mesh::ARRAY_TEX_UV] = uvs;\n\t\t}\n\t\tif (uv2s.size()) {\n\t\t\tarr[Mesh::ARRAY_TEX_UV2] = uv2s;\n\t\t}\n\t\tarr[Mesh::ARRAY_INDEX] = inds;\n\n\t\tam->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr, Array(), Mesh::ARRAY_COMPRESS_DEFAULT);\n\t} \/\/ for s through surfaces\n\n\t\/\/ set all the surfaces on the mesh\n\tset_mesh(am);\n\n\t\/\/ set merged materials\n\tint num_surfaces = first->get_mesh()->get_surface_count();\n\tfor (int n = 0; n < num_surfaces; n++) {\n\t\tset_surface_material(n, first->get_active_material(n));\n\t}\n\n\t\/\/ set some properties to match the merged meshes\n\tset_material_overlay(first->get_material_overlay());\n\tset_material_override(first->get_material_override());\n\tset_cast_shadows_setting(first->get_cast_shadows_setting());\n\tset_flag(FLAG_USE_BAKED_LIGHT, first->get_flag(FLAG_USE_BAKED_LIGHT));\n\n\treturn true;\n}\n\nvoid MeshInstance::_merge_log(String p_string) const {\n\tprint_verbose(p_string);\n}\n\nvoid MeshInstance::_bind_methods() {\n\tClassDB::bind_method(D_METHOD(\"set_mesh\", \"mesh\"), &MeshInstance::set_mesh);\n\tClassDB::bind_method(D_METHOD(\"get_mesh\"), &MeshInstance::get_mesh);\n\tClassDB::bind_method(D_METHOD(\"set_skeleton_path\", \"skeleton_path\"), &MeshInstance::set_skeleton_path);\n\tClassDB::bind_method(D_METHOD(\"get_skeleton_path\"), &MeshInstance::get_skeleton_path);\n\tClassDB::bind_method(D_METHOD(\"set_skin\", \"skin\"), &MeshInstance::set_skin);\n\tClassDB::bind_method(D_METHOD(\"get_skin\"), &MeshInstance::get_skin);\n\n\tClassDB::bind_method(D_METHOD(\"get_surface_material_count\"), &MeshInstance::get_surface_material_count);\n\tClassDB::bind_method(D_METHOD(\"set_surface_material\", \"surface\", \"material\"), &MeshInstance::set_surface_material);\n\tClassDB::bind_method(D_METHOD(\"get_surface_material\", \"surface\"), &MeshInstance::get_surface_material);\n\tClassDB::bind_method(D_METHOD(\"get_active_material\", \"surface\"), &MeshInstance::get_active_material);\n\n\tClassDB::bind_method(D_METHOD(\"set_software_skinning_transform_normals\", \"enabled\"), &MeshInstance::set_software_skinning_transform_normals);\n\tClassDB::bind_method(D_METHOD(\"is_software_skinning_transform_normals_enabled\"), &MeshInstance::is_software_skinning_transform_normals_enabled);\n\n\tClassDB::bind_method(D_METHOD(\"create_trimesh_collision\"), &MeshInstance::create_trimesh_collision);\n\tClassDB::set_method_flags(\"MeshInstance\", \"create_trimesh_collision\", METHOD_FLAGS_DEFAULT);\n\tClassDB::bind_method(D_METHOD(\"create_multiple_convex_collisions\"), &MeshInstance::create_multiple_convex_collisions);\n\tClassDB::set_method_flags(\"MeshInstance\", \"create_multiple_convex_collisions\", METHOD_FLAGS_DEFAULT);\n\tClassDB::bind_method(D_METHOD(\"create_convex_collision\", \"clean\", \"simplify\"), &MeshInstance::create_convex_collision, DEFVAL(true), DEFVAL(false));\n\tClassDB::set_method_flags(\"MeshInstance\", \"create_convex_collision\", METHOD_FLAGS_DEFAULT);\n\tClassDB::bind_method(D_METHOD(\"_mesh_changed\"), &MeshInstance::_mesh_changed);\n\tClassDB::bind_method(D_METHOD(\"_update_skinning\"), &MeshInstance::_update_skinning);\n\n\tClassDB::bind_method(D_METHOD(\"create_debug_tangents\"), &MeshInstance::create_debug_tangents);\n\tClassDB::set_method_flags(\"MeshInstance\", \"create_debug_tangents\", METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);\n\n\tADD_PROPERTY(PropertyInfo(Variant::OBJECT, \"mesh\", PROPERTY_HINT_RESOURCE_TYPE, \"Mesh\"), \"set_mesh\", \"get_mesh\");\n\tADD_PROPERTY(PropertyInfo(Variant::OBJECT, \"skin\", PROPERTY_HINT_RESOURCE_TYPE, \"Skin\"), \"set_skin\", \"get_skin\");\n\tADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, \"skeleton\", PROPERTY_HINT_NODE_PATH_VALID_TYPES, \"Skeleton\"), \"set_skeleton_path\", \"get_skeleton_path\");\n\n\tADD_GROUP(\"Software Skinning\", \"software_skinning\");\n\tADD_PROPERTY(PropertyInfo(Variant::BOOL, \"software_skinning_transform_normals\"), \"set_software_skinning_transform_normals\", \"is_software_skinning_transform_normals_enabled\");\n}\n\nMeshInstance::MeshInstance() {\n\tskeleton_path = NodePath(\"..\");\n\tsoftware_skinning = nullptr;\n\tsoftware_skinning_flags = SoftwareSkinning::FLAG_TRANSFORM_NORMALS;\n}\n\nMeshInstance::~MeshInstance() {\n\tif (software_skinning) {\n\t\tmemdelete(software_skinning);\n\t\tsoftware_skinning = nullptr;\n\t}\n}\n","avg_line_length":33.6588679245,"max_line_length":321,"alphanum_fraction":0.7123637831} {"size":2745,"ext":"cpp","lang":"C++","max_stars_count":17.0,"content":"\/*******************************************************************************\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n#include \n#include \n\n#include \"net_adoptopenjdk_bumblebench_jni_CallOverheadTestcases.h\"\n#include \"Portal.h\"\n\nvoid Java_net_adoptopenjdk_bumblebench_jni_CallOverheadTestcases_testNoParamNoRet(\n\t\tJNIEnv * env, jobject jobj) {\n\treturn;\n}\n\nvoid Java_net_adoptopenjdk_bumblebench_jni_CallOverheadTestcases_testParamNoRet(\n\t\tJNIEnv* env, jobject jobj, jlong val) {\n\tval += 22;\n\n\treturn;\n}\n\njdouble Java_net_adoptopenjdk_bumblebench_jni_CallOverheadTestcases_testParamAndRet(\n\t\tJNIEnv* env, jobject jobj, jlong jl, jint ji, jboolean jbool, jbyte jb,\n\t\tjchar jc, jshort js, jfloat jf1, jfloat jf2, jfloat jf3, jfloat jf4,\n\t\tjfloat jf5, jdouble jd1, jdouble jd2, jdouble jd3) {\n\n\tji += 2;\n\n\tjdouble retVal = 0;\n\n\tif ((ji + jl) >= (jf1 + jf2 + jf5)) {\n\t\tretVal = jd1 + jd2;\n\t} else {\n\t\tretVal = jd2;\n\t}\n\n\treturn retVal;\n}\n\n\/\/ this is a non-static function that sets a non-static longField to the input value\nvoid Java_net_adoptopenjdk_bumblebench_jni_CallOverheadTestcases_testSetLongField(\n\t\tJNIEnv* env, jobject jobj, jlong val) {\n\n\tJNIBenchmark::CallOverheadPortal::setLongHandle(env, jobj, val,\n\t\t\t\"longField\");\n\treturn;\n}\n\n\/\/ this is a static call that sets a static long field to the input value\nvoid Java_net_adoptopenjdk_bumblebench_jni_CallOverheadTestcases_testSetLongFieldStatic(\n\t\tJNIEnv* env, jclass jcls, jlong val) {\n\n\tJNIBenchmark::CallOverheadPortal::setStaticLongHandle(env, jcls, val,\n\t\t\t\"longFieldStatic\");\n\treturn;\n}\n\n\/\/ test: avoiding full array copies\n\/\/ takes an input array of long, add val to each element and writes the result back to\n\/\/ a output long[] via jni\nvoid Java_net_adoptopenjdk_bumblebench_jni_CallOverheadTestcases_testArrayReadWriteRegion(\n\t\tJNIEnv* env, jobject jobj, jlongArray input, jlong val,\n\t\tjlongArray output, jint len) {\n\n\tjlong inputRegion[len];\n\tjlong outputRegion[len];\n\n\tenv->GetLongArrayRegion(input, 0, len, inputRegion);\n\n\tfor (jsize i = 0; i < len; ++i) {\n\t\toutputRegion[i] = inputRegion[i] + val;\n\t}\n\n\tenv->SetLongArrayRegion(output, 0, len, outputRegion);\n\treturn;\n}\n","avg_line_length":31.5517241379,"max_line_length":90,"alphanum_fraction":0.7143897996} {"size":38024,"ext":"cpp","lang":"C++","max_stars_count":10.0,"content":"\ufeff\/****************************************************************************\nCopyright (c) 2008-2010 Ricardo Quesada\nCopyright (c) 2010-2013 cocos2d-x.org\nCopyright (c) 2011 Zynga Inc.\nCopyright (c) 2013-2015 Chukong Technologies Inc.\n\nhttp:\/\/www.cocos2d-x.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n****************************************************************************\/\n\n\/\/ cocos2d includes\n#include \"base\/CCDirector.h\"\n\n\/\/ standard includes\n#include \n\n#include \"2d\/CCDrawingPrimitives.h\"\n#include \"2d\/CCSpriteFrameCache.h\"\n#include \"platform\/CCFileUtils.h\"\n\n#include \"2d\/CCActionManager.h\"\n#include \"2d\/CCFontFNT.h\"\n#include \"2d\/CCFontAtlasCache.h\"\n#include \"2d\/CCAnimationCache.h\"\n#include \"2d\/CCTransition.h\"\n#include \"2d\/CCFontFreeType.h\"\n#include \"2d\/CCLabelAtlas.h\"\n#include \"renderer\/CCGLProgramCache.h\"\n#include \"renderer\/CCGLProgramStateCache.h\"\n#include \"renderer\/CCTextureCache.h\"\n#include \"renderer\/ccGLStateCache.h\"\n#include \"renderer\/CCRenderer.h\"\n#include \"renderer\/CCRenderState.h\"\n#include \"renderer\/CCFrameBuffer.h\"\n#include \"2d\/CCCamera.h\"\n#include \"base\/CCUserDefault.h\"\n#include \"base\/ccFPSImages.h\"\n#include \"base\/CCScheduler.h\"\n#include \"base\/ccMacros.h\"\n#include \"base\/CCEventDispatcher.h\"\n#include \"base\/CCEventCustom.h\"\n#include \"base\/CCConsole.h\"\n#include \"base\/CCAutoreleasePool.h\"\n#include \"base\/CCConfiguration.h\"\n#include \"base\/CCAsyncTaskPool.h\"\n#include \"platform\/CCApplication.h\"\n\n#if CC_ENABLE_SCRIPT_BINDING\n#include \"base\/CCScriptSupport.h\"\n#endif\n\n\/**\n Position of the FPS\n \n Default: 0,0 (bottom-left corner)\n *\/\n#ifndef CC_DIRECTOR_STATS_POSITION\n#define CC_DIRECTOR_STATS_POSITION Director::getInstance()->getVisibleOrigin()\n#endif \/\/ CC_DIRECTOR_STATS_POSITION\n\nusing namespace std;\n\nNS_CC_BEGIN\n\/\/ FIXME: it should be a Director ivar. Move it there once support for multiple directors is added\n\n\/\/ singleton stuff\nstatic DisplayLinkDirector *s_SharedDirector = nullptr;\n\n#define kDefaultFPS 60 \/\/ 60 frames per second\nextern const char* cocos2dVersion(void);\n\nconst char *Director::EVENT_PROJECTION_CHANGED = \"director_projection_changed\";\nconst char *Director::EVENT_AFTER_DRAW = \"director_after_draw\";\nconst char *Director::EVENT_AFTER_VISIT = \"director_after_visit\";\nconst char *Director::EVENT_BEFORE_UPDATE = \"director_before_update\";\nconst char *Director::EVENT_AFTER_UPDATE = \"director_after_update\";\nconst char *Director::EVENT_RESET = \"director_reset\";\n\nDirector* Director::getInstance()\n{\n if (!s_SharedDirector)\n {\n s_SharedDirector = new (std::nothrow) DisplayLinkDirector();\n CCASSERT(s_SharedDirector, \"FATAL: Not enough memory\");\n s_SharedDirector->init();\n }\n\n return s_SharedDirector;\n}\n\nDirector::Director()\n: _isStatusLabelUpdated(true)\n{\n}\n\nbool Director::init(void)\n{\n setDefaultValues();\n\n \/\/ scenes\n _runningScene = nullptr;\n _nextScene = nullptr;\n\n _notificationNode = nullptr;\n\n _scenesStack.reserve(15);\n\n \/\/ FPS\n _accumDt = 0.0f;\n _frameRate = 0.0f;\n _FPSLabel = _drawnBatchesLabel = _drawnVerticesLabel = nullptr;\n _totalFrames = 0;\n _lastUpdate = std::chrono::steady_clock::now();\n _secondsPerFrame = 1.0f;\n\n \/\/ paused ?\n _paused = false;\n\n \/\/ purge ?\n _purgeDirectorInNextLoop = false;\n \n \/\/ restart ?\n _restartDirectorInNextLoop = false;\n\n _winSizeInPoints = Size::ZERO;\n\n _openGLView = nullptr;\n _defaultFBO = nullptr;\n \n _contentScaleFactor = 1.0f;\n\n _console = new (std::nothrow) Console;\n\n \/\/ scheduler\n _scheduler = new (std::nothrow) Scheduler();\n \/\/ action manager\n _actionManager = new (std::nothrow) ActionManager();\n _scheduler->scheduleUpdate(_actionManager, Scheduler::PRIORITY_SYSTEM, false);\n\n _eventDispatcher = new (std::nothrow) EventDispatcher();\n _eventAfterDraw = new (std::nothrow) EventCustom(EVENT_AFTER_DRAW);\n _eventAfterDraw->setUserData(this);\n _eventAfterVisit = new (std::nothrow) EventCustom(EVENT_AFTER_VISIT);\n _eventAfterVisit->setUserData(this);\n _eventBeforeUpdate = new (std::nothrow) EventCustom(EVENT_BEFORE_UPDATE);\n _eventBeforeUpdate->setUserData(this);\n _eventAfterUpdate = new (std::nothrow) EventCustom(EVENT_AFTER_UPDATE);\n _eventAfterUpdate->setUserData(this);\n _eventProjectionChanged = new (std::nothrow) EventCustom(EVENT_PROJECTION_CHANGED);\n _eventProjectionChanged->setUserData(this);\n _eventResetDirector = new (std::nothrow) EventCustom(EVENT_RESET);\n \/\/init TextureCache\n initTextureCache();\n initMatrixStack();\n\n _renderer = new (std::nothrow) Renderer;\n RenderState::initialize();\n\n return true;\n}\n\nDirector::~Director(void)\n{\n CCLOGINFO(\"deallocing Director: %p\", this);\n\n CC_SAFE_RELEASE(_FPSLabel);\n CC_SAFE_RELEASE(_drawnVerticesLabel);\n CC_SAFE_RELEASE(_drawnBatchesLabel);\n\n CC_SAFE_RELEASE(_runningScene);\n CC_SAFE_RELEASE(_notificationNode);\n CC_SAFE_RELEASE(_scheduler);\n CC_SAFE_RELEASE(_actionManager);\n CC_SAFE_DELETE(_defaultFBO);\n \n delete _eventBeforeUpdate;\n delete _eventAfterUpdate;\n delete _eventAfterDraw;\n delete _eventAfterVisit;\n delete _eventProjectionChanged;\n delete _eventResetDirector;\n\n delete _renderer;\n\n delete _console;\n\n\n CC_SAFE_RELEASE(_eventDispatcher);\n \n Configuration::destroyInstance();\n\n s_SharedDirector = nullptr;\n}\n\nvoid Director::setDefaultValues(void)\n{\n Configuration *conf = Configuration::getInstance();\n\n \/\/ default FPS\n double fps = conf->getValue(\"cocos2d.x.fps\", Value(kDefaultFPS)).asDouble();\n _oldAnimationInterval = _animationInterval = 1.0 \/ fps;\n\n \/\/ Display FPS\n _displayStats = conf->getValue(\"cocos2d.x.display_fps\", Value(false)).asBool();\n\n \/\/ GL projection\n std::string projection = conf->getValue(\"cocos2d.x.gl.projection\", Value(\"3d\")).asString();\n if (projection == \"3d\")\n _projection = Projection::_3D;\n else if (projection == \"2d\")\n _projection = Projection::_2D;\n else if (projection == \"custom\")\n _projection = Projection::CUSTOM;\n else\n CCASSERT(false, \"Invalid projection value\");\n\n \/\/ Default pixel format for PNG images with alpha\n std::string pixel_format = conf->getValue(\"cocos2d.x.texture.pixel_format_for_png\", Value(\"rgba8888\")).asString();\n if (pixel_format == \"rgba8888\")\n Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888);\n else if(pixel_format == \"rgba4444\")\n Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444);\n else if(pixel_format == \"rgba5551\")\n Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB5A1);\n\n \/\/ PVR v2 has alpha premultiplied ?\n bool pvr_alpha_premultipled = conf->getValue(\"cocos2d.x.texture.pvrv2_has_alpha_premultiplied\", Value(false)).asBool();\n Image::setPVRImagesHavePremultipliedAlpha(pvr_alpha_premultipled);\n}\n\nvoid Director::setGLDefaultValues()\n{\n \/\/ This method SHOULD be called only after openGLView_ was initialized\n CCASSERT(_openGLView, \"opengl view should not be null\");\n\n setAlphaBlending(true);\n setDepthTest(false);\n setProjection(_projection);\n}\n\n\/\/ Draw the Scene\nvoid Director::drawScene()\n{\n \/\/ calculate \"global\" dt\n calculateDeltaTime();\n \n if (_openGLView)\n {\n _openGLView->pollEvents();\n }\n\n \/\/tick before glClear: issue #533\n if (! _paused)\n {\n _eventDispatcher->dispatchEvent(_eventBeforeUpdate);\n _scheduler->update(_deltaTime);\n _eventDispatcher->dispatchEvent(_eventAfterUpdate);\n }\n\n _renderer->clear();\n experimental::FrameBuffer::clearAllFBOs();\n \/* to avoid flickr, nextScene MUST be here: after tick and before draw.\n * FIXME: Which bug is this one. It seems that it can't be reproduced with v0.9\n *\/\n if (_nextScene)\n {\n setNextScene();\n }\n\n pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);\n \n if (_runningScene)\n {\n#if (CC_USE_PHYSICS || (CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION) || CC_USE_NAVMESH)\n _runningScene->stepPhysicsAndNavigation(_deltaTime);\n#endif\n \/\/clear draw stats\n _renderer->clearDrawStats();\n \n \/\/render the scene\n _openGLView->renderScene(_runningScene, _renderer);\n \n _eventDispatcher->dispatchEvent(_eventAfterVisit);\n }\n\n \/\/ draw the notifications node\n if (_notificationNode)\n {\n _notificationNode->visit(_renderer, Mat4::IDENTITY, 0);\n }\n\n if (_displayStats)\n {\n showStats();\n }\n _renderer->render();\n\n _eventDispatcher->dispatchEvent(_eventAfterDraw);\n\n popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);\n\n _totalFrames++;\n\n \/\/ swap buffers\n if (_openGLView)\n {\n _openGLView->swapBuffers();\n }\n\n if (_displayStats)\n {\n calculateMPF();\n }\n}\n\nvoid Director::calculateDeltaTime()\n{\n auto now = std::chrono::steady_clock::now();\n\n \/\/ new delta time. Re-fixed issue #1277\n if (_nextDeltaTimeZero)\n {\n _deltaTime = 0;\n _nextDeltaTimeZero = false;\n }\n else\n {\n _deltaTime = std::chrono::duration_cast(now - _lastUpdate).count() \/ 1000000.0f;\n _deltaTime = MAX(0, _deltaTime);\n }\n\n#if COCOS2D_DEBUG\n \/\/ If we are debugging our code, prevent big delta time\n if (_deltaTime > 0.2f)\n {\n _deltaTime = 1 \/ 60.0f;\n }\n#endif\n\n _lastUpdate = now;\n}\nfloat Director::getDeltaTime() const\n{\n return _deltaTime;\n}\nvoid Director::setOpenGLView(GLView *openGLView)\n{\n CCASSERT(openGLView, \"opengl view should not be null\");\n\n if (_openGLView != openGLView)\n {\n \/\/ Configuration. Gather GPU info\n Configuration *conf = Configuration::getInstance();\n conf->gatherGPUInfo();\n CCLOG(\"%s\\n\",conf->getInfo().c_str());\n\n if(_openGLView)\n _openGLView->release();\n _openGLView = openGLView;\n _openGLView->retain();\n\n \/\/ set size\n _winSizeInPoints = _openGLView->getDesignResolutionSize();\n\n _isStatusLabelUpdated = true;\n\n if (_openGLView)\n {\n setGLDefaultValues();\n }\n\n _renderer->initGLView();\n\n CHECK_GL_ERROR_DEBUG();\n\n if (_eventDispatcher)\n {\n _eventDispatcher->setEnabled(true);\n }\n \n _defaultFBO = experimental::FrameBuffer::getOrCreateDefaultFBO(_openGLView);\n _defaultFBO->retain();\n }\n}\n\nTextureCache* Director::getTextureCache() const\n{\n return _textureCache;\n}\n\nvoid Director::initTextureCache()\n{\n _textureCache = new (std::nothrow) TextureCache();\n}\n\nvoid Director::destroyTextureCache()\n{\n if (_textureCache)\n {\n _textureCache->waitForQuit();\n CC_SAFE_RELEASE_NULL(_textureCache);\n }\n}\n\nvoid Director::setViewport()\n{\n if (_openGLView)\n {\n _openGLView->setViewPortInPoints(0, 0, _winSizeInPoints.width, _winSizeInPoints.height);\n }\n}\n\nvoid Director::setNextDeltaTimeZero(bool nextDeltaTimeZero)\n{\n _nextDeltaTimeZero = nextDeltaTimeZero;\n}\n\n\/\/\n\/\/ FIXME TODO\n\/\/ Matrix code MUST NOT be part of the Director\n\/\/ MUST BE moved outside.\n\/\/ Why the Director must have this code ?\n\/\/\nvoid Director::initMatrixStack()\n{\n while (!_modelViewMatrixStack.empty())\n {\n _modelViewMatrixStack.pop();\n }\n \n while (!_projectionMatrixStack.empty())\n {\n _projectionMatrixStack.pop();\n }\n \n while (!_textureMatrixStack.empty())\n {\n _textureMatrixStack.pop();\n }\n \n _modelViewMatrixStack.push(Mat4::IDENTITY);\n _projectionMatrixStack.push(Mat4::IDENTITY);\n _textureMatrixStack.push(Mat4::IDENTITY);\n}\n\nvoid Director::resetMatrixStack()\n{\n initMatrixStack();\n}\n\nvoid Director::popMatrix(MATRIX_STACK_TYPE type)\n{\n if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)\n {\n _modelViewMatrixStack.pop();\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)\n {\n _projectionMatrixStack.pop();\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)\n {\n _textureMatrixStack.pop();\n }\n else\n {\n CCASSERT(false, \"unknown matrix stack type\");\n }\n}\n\nvoid Director::loadIdentityMatrix(MATRIX_STACK_TYPE type)\n{\n if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)\n {\n _modelViewMatrixStack.top() = Mat4::IDENTITY;\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)\n {\n _projectionMatrixStack.top() = Mat4::IDENTITY;\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)\n {\n _textureMatrixStack.top() = Mat4::IDENTITY;\n }\n else\n {\n CCASSERT(false, \"unknown matrix stack type\");\n }\n}\n\nvoid Director::loadMatrix(MATRIX_STACK_TYPE type, const Mat4& mat)\n{\n if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)\n {\n _modelViewMatrixStack.top() = mat;\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)\n {\n _projectionMatrixStack.top() = mat;\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)\n {\n _textureMatrixStack.top() = mat;\n }\n else\n {\n CCASSERT(false, \"unknown matrix stack type\");\n }\n}\n\nvoid Director::multiplyMatrix(MATRIX_STACK_TYPE type, const Mat4& mat)\n{\n if(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW == type)\n {\n _modelViewMatrixStack.top() *= mat;\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION == type)\n {\n _projectionMatrixStack.top() *= mat;\n }\n else if(MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE == type)\n {\n _textureMatrixStack.top() *= mat;\n }\n else\n {\n CCASSERT(false, \"unknown matrix stack type\");\n }\n}\n\nvoid Director::pushMatrix(MATRIX_STACK_TYPE type)\n{\n if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW)\n {\n _modelViewMatrixStack.push(_modelViewMatrixStack.top());\n }\n else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION)\n {\n _projectionMatrixStack.push(_projectionMatrixStack.top());\n }\n else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE)\n {\n _textureMatrixStack.push(_textureMatrixStack.top());\n }\n else\n {\n CCASSERT(false, \"unknown matrix stack type\");\n }\n}\n\nconst Mat4& Director::getMatrix(MATRIX_STACK_TYPE type) const\n{\n if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW)\n {\n return _modelViewMatrixStack.top();\n }\n else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION)\n {\n return _projectionMatrixStack.top();\n }\n else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE)\n {\n return _textureMatrixStack.top();\n }\n\n CCASSERT(false, \"unknown matrix stack type, will return modelview matrix instead\");\n return _modelViewMatrixStack.top();\n}\n\nvoid Director::setProjection(Projection projection)\n{\n Size size = _winSizeInPoints;\n\n if (size.width == 0 || size.height == 0)\n {\n CCLOGERROR(\"cocos2d: warning, Director::setProjection() failed because size is 0\");\n return;\n }\n\n setViewport();\n\n switch (projection)\n {\n case Projection::_2D:\n {\n Mat4 orthoMatrix;\n Mat4::createOrthographicOffCenter(0, size.width, 0, size.height, -1024, 1024, &orthoMatrix);\n loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, orthoMatrix);\n loadIdentityMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);\n break;\n }\n \n case Projection::_3D:\n {\n float zeye = this->getZEye();\n\n Mat4 matrixPerspective, matrixLookup;\n\n \/\/ issue #1334\n Mat4::createPerspective(60, (GLfloat)size.width\/size.height, 10, zeye+size.height\/2, &matrixPerspective);\n\n Vec3 eye(size.width\/2, size.height\/2, zeye), center(size.width\/2, size.height\/2, 0.0f), up(0.0f, 1.0f, 0.0f);\n Mat4::createLookAt(eye, center, up, &matrixLookup);\n Mat4 proj3d = matrixPerspective * matrixLookup;\n\n loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, proj3d);\n loadIdentityMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);\n break;\n }\n\n case Projection::CUSTOM:\n \/\/ Projection Delegate is no longer needed\n \/\/ since the event \"PROJECTION CHANGED\" is emitted\n break;\n\n default:\n CCLOG(\"cocos2d: Director: unrecognized projection\");\n break;\n }\n\n _projection = projection;\n GL::setProjectionMatrixDirty();\n\n _eventDispatcher->dispatchEvent(_eventProjectionChanged);\n}\n\nvoid Director::purgeCachedData(void)\n{\n FontFNT::purgeCachedData();\n FontAtlasCache::purgeCachedData();\n\n if (s_SharedDirector->getOpenGLView())\n {\n SpriteFrameCache::getInstance()->removeUnusedSpriteFrames();\n _textureCache->removeUnusedTextures();\n\n \/\/ Note: some tests such as ActionsTest are leaking refcounted textures\n \/\/ There should be no test textures left in the cache\n log(\"%s\\n\", _textureCache->getCachedTextureInfo().c_str());\n }\n FileUtils::getInstance()->purgeCachedEntries();\n}\n\nfloat Director::getZEye(void) const\n{\n return (_winSizeInPoints.height \/ 1.1566f);\n}\n\nvoid Director::setAlphaBlending(bool on)\n{\n if (on)\n {\n GL::blendFunc(CC_BLEND_SRC, CC_BLEND_DST);\n }\n else\n {\n GL::blendFunc(GL_ONE, GL_ZERO);\n }\n\n CHECK_GL_ERROR_DEBUG();\n}\n\nvoid Director::setDepthTest(bool on)\n{\n _renderer->setDepthTest(on);\n}\n\nvoid Director::setClearColor(const Color4F& clearColor)\n{\n _renderer->setClearColor(clearColor);\n auto defaultFBO = experimental::FrameBuffer::getOrCreateDefaultFBO(_openGLView);\n \n if(defaultFBO) defaultFBO->setClearColor(clearColor);\n}\n\nstatic void GLToClipTransform(Mat4 *transformOut)\n{\n if(nullptr == transformOut) return;\n \n Director* director = Director::getInstance();\n CCASSERT(nullptr != director, \"Director is null when setting matrix stack\");\n\n auto projection = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);\n auto modelview = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);\n *transformOut = projection * modelview;\n}\n\nVec2 Director::convertToGL(const Vec2& uiPoint)\n{\n Mat4 transform;\n GLToClipTransform(&transform);\n\n Mat4 transformInv = transform.getInversed();\n\n \/\/ Calculate z=0 using -> transform*[0, 0, 0, 1]\/w\n float zClip = transform.m[14]\/transform.m[15];\n\n Size glSize = _openGLView->getDesignResolutionSize();\n Vec4 clipCoord(2.0f*uiPoint.x\/glSize.width - 1.0f, 1.0f - 2.0f*uiPoint.y\/glSize.height, zClip, 1);\n\n Vec4 glCoord;\n \/\/transformInv.transformPoint(clipCoord, &glCoord);\n transformInv.transformVector(clipCoord, &glCoord);\n float factor = 1.0f \/ glCoord.w;\n return Vec2(glCoord.x * factor, glCoord.y * factor);\n}\n\nVec2 Director::convertToUI(const Vec2& glPoint)\n{\n Mat4 transform;\n GLToClipTransform(&transform);\n\n Vec4 clipCoord;\n \/\/ Need to calculate the zero depth from the transform.\n Vec4 glCoord(glPoint.x, glPoint.y, 0.0, 1);\n transform.transformVector(glCoord, &clipCoord);\n\n\t\/*\n\tBUG-FIX #5506\n\n\ta = (Vx, Vy, Vz, 1)\n\tb = (a\u00d7M)T\n\tOut = 1 \u2044 bw(bx, by, bz)\n\t*\/\n\t\n\tclipCoord.x = clipCoord.x \/ clipCoord.w;\n\tclipCoord.y = clipCoord.y \/ clipCoord.w;\n\tclipCoord.z = clipCoord.z \/ clipCoord.w;\n\n Size glSize = _openGLView->getDesignResolutionSize();\n float factor = 1.0f \/ glCoord.w;\n return Vec2(glSize.width * (clipCoord.x * 0.5f + 0.5f) * factor, glSize.height * (-clipCoord.y * 0.5f + 0.5f) * factor);\n}\n\nconst Size& Director::getWinSize(void) const\n{\n return _winSizeInPoints;\n}\n\nSize Director::getWinSizeInPixels() const\n{\n return Size(_winSizeInPoints.width * _contentScaleFactor, _winSizeInPoints.height * _contentScaleFactor);\n}\n\nSize Director::getVisibleSize() const\n{\n if (_openGLView)\n {\n return _openGLView->getVisibleSize();\n }\n else\n {\n return Size::ZERO;\n }\n}\n\nVec2 Director::getVisibleOrigin() const\n{\n if (_openGLView)\n {\n return _openGLView->getVisibleOrigin();\n }\n else\n {\n return Vec2::ZERO;\n }\n}\n\n\/\/ scene management\n\nvoid Director::runWithScene(Scene *scene)\n{\n CCASSERT(scene != nullptr, \"This command can only be used to start the Director. There is already a scene present.\");\n CCASSERT(_runningScene == nullptr, \"_runningScene should be null\");\n\n pushScene(scene);\n startAnimation();\n}\n\nvoid Director::replaceScene(Scene *scene)\n{\n \/\/CCASSERT(_runningScene, \"Use runWithScene: instead to start the director\");\n CCASSERT(scene != nullptr, \"the scene should not be null\");\n \n if (_runningScene == nullptr) {\n runWithScene(scene);\n return;\n }\n \n if (scene == _nextScene)\n return;\n \n if (_nextScene)\n {\n if (_nextScene->isRunning())\n {\n _nextScene->onExit();\n }\n _nextScene->cleanup();\n _nextScene = nullptr;\n }\n\n ssize_t index = _scenesStack.size() - 1;\n\n _sendCleanupToScene = true;\n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();\n if (sEngine)\n {\n sEngine->retainScriptObject(this, scene);\n sEngine->releaseScriptObject(this, _scenesStack.at(index));\n }\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n _scenesStack.replace(index, scene);\n\n _nextScene = scene;\n}\n\nvoid Director::pushScene(Scene *scene)\n{\n CCASSERT(scene, \"the scene should not null\");\n\n _sendCleanupToScene = false;\n\n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();\n if (sEngine)\n {\n sEngine->retainScriptObject(this, scene);\n }\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n _scenesStack.pushBack(scene);\n _nextScene = scene;\n}\n\nvoid Director::popScene(void)\n{\n CCASSERT(_runningScene != nullptr, \"running scene should not null\");\n \n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();\n if (sEngine)\n {\n sEngine->releaseScriptObject(this, _scenesStack.back());\n }\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n _scenesStack.popBack();\n ssize_t c = _scenesStack.size();\n\n if (c == 0)\n {\n end();\n }\n else\n {\n _sendCleanupToScene = true;\n _nextScene = _scenesStack.at(c - 1);\n }\n}\n\nvoid Director::popToRootScene(void)\n{\n popToSceneStackLevel(1);\n}\n\nvoid Director::popToSceneStackLevel(int level)\n{\n CCASSERT(_runningScene != nullptr, \"A running Scene is needed\");\n ssize_t c = _scenesStack.size();\n\n \/\/ level 0? -> end\n if (level == 0)\n {\n end();\n return;\n }\n\n \/\/ current level or lower -> nothing\n if (level >= c)\n return;\n\n auto firstOnStackScene = _scenesStack.back();\n if (firstOnStackScene == _runningScene)\n {\n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();\n if (sEngine)\n {\n sEngine->releaseScriptObject(this, _scenesStack.back());\n }\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n _scenesStack.popBack();\n --c;\n }\n\n \/\/ pop stack until reaching desired level\n while (c > level)\n {\n auto current = _scenesStack.back();\n\n if (current->isRunning())\n {\n current->onExit();\n }\n\n current->cleanup();\n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();\n if (sEngine)\n {\n sEngine->releaseScriptObject(this, _scenesStack.back());\n }\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n _scenesStack.popBack();\n --c;\n }\n\n _nextScene = _scenesStack.back();\n\n \/\/ cleanup running scene\n _sendCleanupToScene = true;\n}\n\nvoid Director::end()\n{\n _purgeDirectorInNextLoop = true;\n}\n\nvoid Director::restart()\n{\n _restartDirectorInNextLoop = true;\n}\n\nvoid Director::reset()\n{\n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n \n if (_runningScene)\n {\n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n if (sEngine)\n {\n sEngine->releaseScriptObject(this, _runningScene);\n }\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n _runningScene->onExit();\n _runningScene->cleanup();\n _runningScene->release();\n }\n \n _runningScene = nullptr;\n _nextScene = nullptr;\n\n _eventDispatcher->dispatchEvent(_eventResetDirector);\n \n \/\/ cleanup scheduler\n getScheduler()->unscheduleAll();\n \n \/\/ Remove all events\n if (_eventDispatcher)\n {\n _eventDispatcher->removeAllEventListeners();\n }\n \n \/\/ remove all objects, but don't release it.\n \/\/ runWithScene might be executed after 'end'.\n#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n if (sEngine)\n {\n for (const auto &scene : _scenesStack)\n {\n if (scene)\n sEngine->releaseScriptObject(this, scene);\n }\n }\n#endif \/\/ CC_ENABLE_GC_FOR_NATIVE_OBJECTS\n _scenesStack.clear();\n \n stopAnimation();\n \n CC_SAFE_RELEASE_NULL(_notificationNode);\n CC_SAFE_RELEASE_NULL(_FPSLabel);\n CC_SAFE_RELEASE_NULL(_drawnBatchesLabel);\n CC_SAFE_RELEASE_NULL(_drawnVerticesLabel);\n \n \/\/ purge bitmap cache\n FontFNT::purgeCachedData();\n FontAtlasCache::purgeCachedData();\n \n FontFreeType::shutdownFreeType();\n \n \/\/ purge all managed caches\n \n#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#elif _MSC_VER >= 1400 \/\/vs 2005 or higher\n#pragma warning (push)\n#pragma warning (disable: 4996)\n#endif\n\/\/it will crash clang static analyzer so hide it if __clang_analyzer__ defined\n#ifndef __clang_analyzer__\n DrawPrimitives::free();\n#endif\n#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))\n#pragma GCC diagnostic warning \"-Wdeprecated-declarations\"\n#elif _MSC_VER >= 1400 \/\/vs 2005 or higher\n#pragma warning (pop)\n#endif\n AnimationCache::destroyInstance();\n SpriteFrameCache::destroyInstance();\n GLProgramCache::destroyInstance();\n GLProgramStateCache::destroyInstance();\n FileUtils::destroyInstance();\n AsyncTaskPool::destroyInstance();\n \n \/\/ cocos2d-x specific data structures\n UserDefault::destroyInstance();\n \n GL::invalidateStateCache();\n\n RenderState::finalize();\n \n destroyTextureCache();\n}\n\nvoid Director::purgeDirector()\n{\n reset();\n\n CHECK_GL_ERROR_DEBUG();\n \n \/\/ OpenGL view\n if (_openGLView)\n {\n _openGLView->end();\n _openGLView = nullptr;\n }\n\n \/\/ delete Director\n release();\n}\n\nvoid Director::restartDirector()\n{\n reset();\n \n \/\/ RenderState need to be reinitialized\n RenderState::initialize();\n\n \/\/ Texture cache need to be reinitialized\n initTextureCache();\n \n \/\/ Reschedule for action manager\n getScheduler()->scheduleUpdate(getActionManager(), Scheduler::PRIORITY_SYSTEM, false);\n \n \/\/ release the objects\n PoolManager::getInstance()->getCurrentPool()->clear();\n\n \/\/ Restart animation\n startAnimation();\n \n \/\/ Real restart in script level\n#if CC_ENABLE_SCRIPT_BINDING\n ScriptEvent scriptEvent(kRestartGame, nullptr);\n ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);\n#endif\n}\n\nvoid Director::setNextScene()\n{\n bool runningIsTransition = dynamic_cast(_runningScene) != nullptr;\n bool newIsTransition = dynamic_cast(_nextScene) != nullptr;\n\n \/\/ If it is not a transition, call onExit\/cleanup\n if (! newIsTransition)\n {\n if (_runningScene)\n {\n _runningScene->onExitTransitionDidStart();\n _runningScene->onExit();\n }\n \n \/\/ issue #709. the root node (scene) should receive the cleanup message too\n \/\/ otherwise it might be leaked.\n if (_sendCleanupToScene && _runningScene)\n {\n _runningScene->cleanup();\n }\n }\n\n if (_runningScene)\n {\n _runningScene->release();\n }\n _runningScene = _nextScene;\n _nextScene->retain();\n _nextScene = nullptr;\n\n if ((! runningIsTransition) && _runningScene)\n {\n _runningScene->onEnter();\n _runningScene->onEnterTransitionDidFinish();\n }\n}\n\nvoid Director::pause()\n{\n if (_paused)\n {\n return;\n }\n\n _oldAnimationInterval = _animationInterval;\n\n \/\/ when paused, don't consume CPU\n setAnimationInterval(1 \/ 4.0);\n _paused = true;\n}\n\nvoid Director::resume()\n{\n if (! _paused)\n {\n return;\n }\n\n setAnimationInterval(_oldAnimationInterval);\n\n _paused = false;\n _deltaTime = 0;\n \/\/ fix issue #3509, skip one fps to avoid incorrect time calculation.\n setNextDeltaTimeZero(true);\n}\n\n\/\/ display the FPS using a LabelAtlas\n\/\/ updates the FPS every frame\nvoid Director::showStats()\n{\n if (_isStatusLabelUpdated)\n {\n createStatsLabel();\n _isStatusLabelUpdated = false;\n }\n\n static unsigned long prevCalls = 0;\n static unsigned long prevVerts = 0;\n static float prevDeltaTime = 0.016f; \/\/ 60FPS\n static const float FPS_FILTER = 0.10f;\n\n _accumDt += _deltaTime;\n \n if (_displayStats && _FPSLabel && _drawnBatchesLabel && _drawnVerticesLabel)\n {\n char buffer[30];\n\n float dt = _deltaTime * FPS_FILTER + (1-FPS_FILTER) * prevDeltaTime;\n prevDeltaTime = dt;\n _frameRate = 1\/dt;\n\n \/\/ Probably we don't need this anymore since\n \/\/ the framerate is using a low-pass filter\n \/\/ to make the FPS stable\n if (_accumDt > CC_DIRECTOR_STATS_INTERVAL)\n {\n sprintf(buffer, \"%.1f \/ %.3f\", _frameRate, _secondsPerFrame);\n _FPSLabel->setString(buffer);\n _accumDt = 0;\n }\n\n auto currentCalls = (unsigned long)_renderer->getDrawnBatches();\n auto currentVerts = (unsigned long)_renderer->getDrawnVertices();\n if( currentCalls != prevCalls ) {\n sprintf(buffer, \"GL calls:%6lu\", currentCalls);\n _drawnBatchesLabel->setString(buffer);\n prevCalls = currentCalls;\n }\n\n if( currentVerts != prevVerts) {\n sprintf(buffer, \"GL verts:%6lu\", currentVerts);\n _drawnVerticesLabel->setString(buffer);\n prevVerts = currentVerts;\n }\n\n const Mat4& identity = Mat4::IDENTITY;\n _drawnVerticesLabel->visit(_renderer, identity, 0);\n _drawnBatchesLabel->visit(_renderer, identity, 0);\n _FPSLabel->visit(_renderer, identity, 0);\n }\n}\n\nvoid Director::calculateMPF()\n{\n static float prevSecondsPerFrame = 0;\n static const float MPF_FILTER = 0.10f;\n\n auto now = std::chrono::steady_clock::now();\n \n _secondsPerFrame = std::chrono::duration_cast(now - _lastUpdate).count() \/ 1000000.0f;\n\n _secondsPerFrame = _secondsPerFrame * MPF_FILTER + (1-MPF_FILTER) * prevSecondsPerFrame;\n prevSecondsPerFrame = _secondsPerFrame;\n}\n\n\/\/ returns the FPS image data pointer and len\nvoid Director::getFPSImageData(unsigned char** datapointer, ssize_t* length)\n{\n \/\/ FIXME: fixed me if it should be used \n *datapointer = cc_fps_images_png;\n *length = cc_fps_images_len();\n}\n\nvoid Director::createStatsLabel()\n{\n Texture2D *texture = nullptr;\n std::string fpsString = \"00.0\";\n std::string drawBatchString = \"000\";\n std::string drawVerticesString = \"00000\";\n if (_FPSLabel)\n {\n fpsString = _FPSLabel->getString();\n drawBatchString = _drawnBatchesLabel->getString();\n drawVerticesString = _drawnVerticesLabel->getString();\n \n CC_SAFE_RELEASE_NULL(_FPSLabel);\n CC_SAFE_RELEASE_NULL(_drawnBatchesLabel);\n CC_SAFE_RELEASE_NULL(_drawnVerticesLabel);\n _textureCache->removeTextureForKey(\"\/cc_fps_images\");\n FileUtils::getInstance()->purgeCachedEntries();\n }\n\n Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat();\n Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444);\n unsigned char *data = nullptr;\n ssize_t dataLength = 0;\n getFPSImageData(&data, &dataLength);\n\n Image* image = new (std::nothrow) Image();\n bool isOK = image->initWithImageData(data, dataLength);\n if (! isOK) {\n CCLOGERROR(\"%s\", \"Fails: init fps_images\");\n return;\n }\n\n texture = _textureCache->addImage(image, \"\/cc_fps_images\");\n CC_SAFE_RELEASE(image);\n\n \/*\n We want to use an image which is stored in the file named ccFPSImage.c \n for any design resolutions and all resource resolutions. \n \n To achieve this, we need to ignore 'contentScaleFactor' in 'AtlasNode' and 'LabelAtlas'.\n So I added a new method called 'setIgnoreContentScaleFactor' for 'AtlasNode',\n this is not exposed to game developers, it's only used for displaying FPS now.\n *\/\n float scaleFactor = 1 \/ CC_CONTENT_SCALE_FACTOR();\n\n _FPSLabel = LabelAtlas::create();\n _FPSLabel->retain();\n _FPSLabel->setIgnoreContentScaleFactor(true);\n _FPSLabel->initWithString(fpsString, texture, 12, 32 , '.');\n _FPSLabel->setScale(scaleFactor);\n\n _drawnBatchesLabel = LabelAtlas::create();\n _drawnBatchesLabel->retain();\n _drawnBatchesLabel->setIgnoreContentScaleFactor(true);\n _drawnBatchesLabel->initWithString(drawBatchString, texture, 12, 32, '.');\n _drawnBatchesLabel->setScale(scaleFactor);\n\n _drawnVerticesLabel = LabelAtlas::create();\n _drawnVerticesLabel->retain();\n _drawnVerticesLabel->setIgnoreContentScaleFactor(true);\n _drawnVerticesLabel->initWithString(drawVerticesString, texture, 12, 32, '.');\n _drawnVerticesLabel->setScale(scaleFactor);\n\n\n Texture2D::setDefaultAlphaPixelFormat(currentFormat);\n\n const int height_spacing = 22 \/ CC_CONTENT_SCALE_FACTOR();\n _drawnVerticesLabel->setPosition(Vec2(0, height_spacing*2) + CC_DIRECTOR_STATS_POSITION);\n _drawnBatchesLabel->setPosition(Vec2(0, height_spacing*1) + CC_DIRECTOR_STATS_POSITION);\n _FPSLabel->setPosition(Vec2(0, height_spacing*0)+CC_DIRECTOR_STATS_POSITION);\n}\n\nvoid Director::setContentScaleFactor(float scaleFactor)\n{\n if (scaleFactor != _contentScaleFactor)\n {\n _contentScaleFactor = scaleFactor;\n _isStatusLabelUpdated = true;\n }\n}\n\nvoid Director::setNotificationNode(Node *node)\n{\n\tif (_notificationNode != nullptr){\n\t\t_notificationNode->onExitTransitionDidStart();\n\t\t_notificationNode->onExit();\n\t\t_notificationNode->cleanup();\n\t}\n\tCC_SAFE_RELEASE(_notificationNode);\n\n\t_notificationNode = node;\n\tif (node == nullptr)\n\t\treturn;\n\t_notificationNode->onEnter();\n\t_notificationNode->onEnterTransitionDidFinish();\n CC_SAFE_RETAIN(_notificationNode);\n}\n\nvoid Director::setScheduler(Scheduler* scheduler)\n{\n if (_scheduler != scheduler)\n {\n CC_SAFE_RETAIN(scheduler);\n CC_SAFE_RELEASE(_scheduler);\n _scheduler = scheduler;\n }\n}\n\nvoid Director::setActionManager(ActionManager* actionManager)\n{\n if (_actionManager != actionManager)\n {\n CC_SAFE_RETAIN(actionManager);\n CC_SAFE_RELEASE(_actionManager);\n _actionManager = actionManager;\n } \n}\n\nvoid Director::setEventDispatcher(EventDispatcher* dispatcher)\n{\n if (_eventDispatcher != dispatcher)\n {\n CC_SAFE_RETAIN(dispatcher);\n CC_SAFE_RELEASE(_eventDispatcher);\n _eventDispatcher = dispatcher;\n }\n}\n\n\/***************************************************\n* implementation of DisplayLinkDirector\n**************************************************\/\n\n\/\/ should we implement 4 types of director ??\n\/\/ I think DisplayLinkDirector is enough\n\/\/ so we now only support DisplayLinkDirector\nvoid DisplayLinkDirector::startAnimation()\n{\n _lastUpdate = std::chrono::steady_clock::now();\n\n _invalid = false;\n\n _cocos2d_thread_id = std::this_thread::get_id();\n\n Application::getInstance()->setAnimationInterval(_animationInterval);\n\n \/\/ fix issue #3509, skip one fps to avoid incorrect time calculation.\n setNextDeltaTimeZero(true);\n}\n\nvoid DisplayLinkDirector::mainLoop()\n{\n if (_purgeDirectorInNextLoop)\n {\n _purgeDirectorInNextLoop = false;\n purgeDirector();\n }\n else if (_restartDirectorInNextLoop)\n {\n _restartDirectorInNextLoop = false;\n restartDirector();\n }\n else if (! _invalid)\n {\n drawScene();\n \n \/\/ release the objects\n PoolManager::getInstance()->getCurrentPool()->clear();\n }\n}\n\nvoid DisplayLinkDirector::stopAnimation()\n{\n _invalid = true;\n}\n\nvoid DisplayLinkDirector::setAnimationInterval(float interval)\n{\n _animationInterval = interval;\n if (! _invalid)\n {\n stopAnimation();\n startAnimation();\n } \n}\n\nNS_CC_END\n\n","avg_line_length":26.8152327221,"max_line_length":124,"alphanum_fraction":0.6700767936} {"size":3290,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n\n#include \n\n#include \n\nnamespace mbgl {\nnamespace util {\n\nnamespace tinysdf {\n\nstatic const double INF = 1e20;\n\n\/\/ 1D squared distance transform\nvoid edt1d(std::vector& f,\n std::vector& d,\n std::vector& v,\n std::vector& z,\n uint32_t n) {\n v[0] = 0;\n z[0] = -INF;\n z[1] = +INF;\n\n for (uint32_t q = 1, k = 0; q < n; q++) {\n double s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) \/ (2 * q - 2 * v[k]);\n while (s <= z[k]) {\n k--;\n s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) \/ (2 * q - 2 * v[k]);\n }\n k++;\n v[k] = q;\n z[k] = s;\n z[k + 1] = +INF;\n }\n\n for (uint32_t q = 0, k = 0; q < n; q++) {\n while (z[k + 1] < q) k++;\n d[q] = (static_cast(q) - v[k]) * (static_cast(q) - v[k]) + f[v[k]];\n }\n}\n\n\n\/\/ 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https:\/\/cs.brown.edu\/~pff\/dt\/\nvoid edt(std::vector& data,\n uint32_t width,\n uint32_t height,\n std::vector& f,\n std::vector& d,\n std::vector& v,\n std::vector& z) {\n for (uint32_t x = 0; x < width; x++) {\n for (uint32_t y = 0; y < height; y++) {\n f[y] = data[y * width + x];\n }\n edt1d(f, d, v, z, height);\n for (uint32_t y = 0; y < height; y++) {\n data[y * width + x] = d[y];\n }\n }\n for (uint32_t y = 0; y < height; y++) {\n for (uint32_t x = 0; x < width; x++) {\n f[x] = data[y * width + x];\n }\n edt1d(f, d, v, z, width);\n for (uint32_t x = 0; x < width; x++) {\n data[y * width + x] = std::sqrt(d[x]);\n }\n }\n}\n\n} \/\/ namespace tinysdf\n\nAlphaImage transformRasterToSDF(const AlphaImage& rasterInput, double radius, double cutoff) {\n uint32_t size = rasterInput.size.width * rasterInput.size.height;\n uint32_t maxDimension = std::max(rasterInput.size.width, rasterInput.size.height);\n \n AlphaImage sdf(rasterInput.size);\n \n \/\/ temporary arrays for the distance transform\n std::vector gridOuter(size);\n std::vector gridInner(size);\n std::vector f(maxDimension);\n std::vector d(maxDimension);\n std::vector z(maxDimension + 1);\n std::vector v(maxDimension);\n \n for (uint32_t i = 0; i < size; i++) {\n double a = static_cast(rasterInput.data[i]) \/ 255; \/\/ alpha value\n gridOuter[i] = a == 1.0 ? 0.0 : a == 0.0 ? tinysdf::INF : std::pow(std::max(0.0, 0.5 - a), 2.0);\n gridInner[i] = a == 1.0 ? tinysdf::INF : a == 0.0 ? 0.0 : std::pow(std::max(0.0, a - 0.5), 2.0);\n }\n\n tinysdf::edt(gridOuter, rasterInput.size.width, rasterInput.size.height, f, d, v, z);\n tinysdf::edt(gridInner, rasterInput.size.width, rasterInput.size.height, f, d, v, z);\n\n for (uint32_t i = 0; i < size; i++) {\n double distance = gridOuter[i] - gridInner[i];\n sdf.data[i] = static_cast(std::max(0l, std::min(255l, ::lround(255.0 - 255.0 * (distance \/ radius + cutoff)))));\n }\n\n return sdf;\n}\n\n} \/\/ namespace util\n} \/\/ namespace mbgl\n","avg_line_length":31.0377358491,"max_line_length":129,"alphanum_fraction":0.5227963526} {"size":6734,"ext":"hpp","lang":"C++","max_stars_count":1.0,"content":"\/*\n * Anti-doublon\n *\/\n#ifndef __OPENKN_MATH__MATH_IO_HPP__\n#define __OPENKN_MATH__MATH_IO_HPP__\n\n\/*\n * External Includes\n *\/\n#include \n#include \n#include \n#include \n#include \n\n#include \"Eigen\/Dense\"\n\nusing namespace Eigen;\n\n\/*\n * Namespace\n *\/\nnamespace kn {\n\n \/**\n * \\cond\n * \\brief ignore the comments and read the header on a matrix file if specified; the user should not use this function.\n * \\param matrixFile the input matrix ifstream\n * \\return true if the matrix format is spefifyed, false otherwise\n * \\throw MathException invalid format\n *\/\n bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &row, unsigned int &column);\n \/\/\/ \\endcond\n\n\n \/**\n * \\cond\n * \\brief ignore the comments and read the header on a matrix file if specified; the user should not use this function.\n * \\param matrixFile the input matrix ifstream\n * \\return true if the matrix format is spefifyed, false otherwise\n * \\throw MathException invalid format\n *\/\n bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &mat);\n \/\/\/ \\endcond\n\n \/**\n * \\brief Load a Matrix from a file. The format is : some optional comments begining by '#', a optional header writing \"row \" and the number of rows, in the next line, \"column \" and the number of columns, and then, line by line, the matrix content.\n * \\param M the Matrix to be loaded\n * \\param fileName the name of the file to open\n * \\throw MathException matrix size is incorrect \/ error opening file \/ invalid format\n *\/\n template \n void loadMatrix(EigenMatrix &M, const std::string &fileName){\n \/\/ open the file\n std::ifstream matrixFile(fileName.c_str());\n if(!matrixFile.is_open()){\n std::cerr << \"error opening file : \" << fileName << std::endl;\n exit(0);\t\t\t\t\n }\n\n \/\/ read header\n unsigned int row = 0;\n unsigned int column = 0;\n bool header = readMatrixHeader(matrixFile,row,column);\n\n \/\/ read the data\n if(header) readMatrixFromHeader(M,matrixFile,row,column);\n else readMatrix(M,matrixFile);\n\n \/\/ close\n matrixFile.close();\n }\n\n \/**\n * \\cond\n * \\brief read the content of a Matrix from the header information (row,col); the user should not use this function.\n * \\param M the Matrix to be filled\n * \\param matrixFile the input matrix ifstream\n * \\param row the expected matrix row number\n * \\param column the expected matrix column number\n * \\throw MathException incompatible matrix size\n *\/\n template \n void readMatrixFromHeader(EigenMatrix &M,\n std::ifstream &matrixFile,\n const unsigned int &row,\n const unsigned int &column) {\n\n \/\/ if the matrix is already build\n if((unsigned int)M.rows() != row || (unsigned int)M.cols() != column)\n M.resize(row,column);\n\t\n \/\/ read the matrix\n for(unsigned int i=0; i> M(i,j);\n }\n \/\/\/ \\endcond\n\n\n \/**\n * \\cond\n * \\brief read the content of a Matrix without any size information (row,col); the user should not use this function.\n * \\param M the Matrix to be filled\n * \\param matrixFile the input matrix ifstream\n * \\throw MathException incompatible matrix size \/ invalid matrix file\n *\/\n template \n void readMatrix(EigenMatrix &M, std::ifstream &matrixFile){\n\n unsigned int row = 0;\n int column = -1; \t\/\/ unknown while you didn't read a line\n\n std::vector content;\n std::string stringContent;\n\n \/\/ first read the matrix in a std::vector to check the consistency of the data\n do{ \/\/ for every line\n std::getline(matrixFile,stringContent);\n std::istringstream readContent(stringContent, std::istringstream::in);\n unsigned int index = 0;\n while(!readContent.eof() && stringContent != \"\"){ \/\/ for every element of a line\n double value;\n readContent >> value;\n content.push_back(value);\n index++;\n }\n\n \/\/ remove the eof\n \/\/content.erase(content.end()-1);\n \/\/index--;\n\n if(column == -1 && index != 0){ \/\/ 1st line : find 'column'\n column = index;\n row++;\n }else{\n if(index != 0){ \/\/ check empty line or invalid column\n if(column != (int)index ){\n std::cerr << \"readMatrix : invalid matrix file\" << std::endl;\n exit(0);\n }else row++;\n }else{\n \/\/Matrix reading complete (empty line found)\n break;\n }\n }\n }\n\n while(!matrixFile.eof());\n\n if(row==0 && column==-1) return;\n\n \/\/ if the matrix is already build\n if((unsigned int)M.rows() != row || M.cols() != column)\n M.resize(row,column);\n\n \/\/ copy the data\n for(unsigned int i=0; i\n void saveMatrix(const EigenMatrix &M,\n const std::string &fileName,\n const bool headerMode = false,\n const std::string &comments = \"\") {\n\n \/\/ open the file\n std::ofstream matrixFile(fileName.c_str());\n if(!matrixFile.is_open()){\n std::cerr << \"error opening file : \" << fileName << std::endl;\n exit(0);\t\t\t\t\n }\n\n \/\/ write comments\n if(comments != \"\")\n matrixFile << \"# \" << comments << std::endl;\n\n \/\/ write header\n if(headerMode)\n matrixFile << \"row \" << M.rows() << std::endl\n << \"col \" << M.cols() << std::endl;\n\n \/\/ additional line \n if(comments != \"\" || headerMode)\n matrixFile << std::endl;\n\n \/\/ write matrix content\n for (unsigned int i=0; i<(unsigned int)M.rows(); ++i){\n for (unsigned int j=0; j<(unsigned int)M.cols(); ++j)\n matrixFile << M(i,j) << \" \";\n\n matrixFile << std::endl;\n }\n\n \/\/ close file\n matrixFile.close();\n }\n\n\n\n \/*\n * End of Namespace\n *\/\n}\n\n\n\/*\n * End of Anti-doublon\n *\/\n#endif\n\n\n\n","avg_line_length":29.6651982379,"max_line_length":250,"alphanum_fraction":0.6192456192} {"size":7917,"ext":"cc","lang":"C++","max_stars_count":null,"content":"\/\/ Copyright 2018 The Fuchsia Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"fake-device.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace fidl_qmi_transport = llcpp::fuchsia::hardware::telephony::transport;\nnamespace fidl_tel_snoop = ::llcpp::fuchsia::telephony::snoop;\n\nnamespace qmi_fake {\nconstexpr uint8_t kQmiInitReq[] = {1, 15, 0, 0, 0, 0, 0, 1, 34, 0, 4, 0, 1, 1, 0, 2};\nconstexpr uint8_t kQmiImeiReq[] = {1, 12, 0, 0, 2, 1, 0, 1, 0, 37, 0, 0, 0};\nconstexpr uint8_t kQmiInitResp[] = {1, 23, 0, 128, 0, 0, 1, 1, 34, 0, 12, 0,\n 2, 4, 0, 0, 0, 0, 0, 1, 2, 0, 2, 1};\nconstexpr uint8_t kQmiImeiResp[] = {1, 41, 0, 128, 2, 1, 2, 1, 0, 37, 0, 29, 0, 2,\n 4, 0, 0, 0, 0, 0, 16, 1, 0, 48, 17, 15, 0, 51,\n 53, 57, 50, 54, 48, 48, 56, 48, 49, 54, 56, 51, 53, 49};\nconstexpr uint8_t kQmiPerioEvent[] = {1, 11, 0, 128, 0, 0, 2, 0, 39, 0, 0, 0};\nconstexpr uint8_t kQmiNonsenseResp[] = {1, 0};\n\nconstexpr uint32_t kTelCtrlPlanePktMax = 2048;\n\nQmiDevice::QmiDevice(zx_device_t* device) : Device(device) {}\n\n#define DEV(c) static_cast(c)\nstatic zx_protocol_device_t qmi_fake_device_ops = {\n .version = DEVICE_OPS_VERSION,\n .get_protocol = [](void* ctx, uint32_t proto_id, void* out_proto) -> zx_status_t {\n return DEV(ctx)->GetProtocol(proto_id, out_proto);\n },\n .unbind = [](void* ctx) { DEV(ctx)->Unbind(); },\n .release = [](void* ctx) { DEV(ctx)->Release(); },\n .message = [](void* ctx, fidl_msg_t* msg, fidl_txn_t* txn) -> zx_status_t {\n return DEV(ctx)->DdkMessage(msg, txn);\n },\n};\n#undef DEV\n\nstatic void sent_fake_qmi_msg(zx::channel& channel, uint8_t* resp, uint32_t resp_size) {\n zx_status_t status;\n status = channel.write(0, resp, resp_size, NULL, 0);\n if (status < 0) {\n zxlogf(ERROR, \"qmi-fake-transport: failed to write message to channel: %s\\n\",\n zx_status_get_string(status));\n }\n}\n\nvoid QmiDevice::SnoopCtrlMsg(uint8_t* snoop_data, uint32_t snoop_data_len,\n fidl_tel_snoop::Direction direction) {\n if (GetCtrlSnoopChannel()) {\n fidl_tel_snoop::Message snoop_msg;\n fidl_tel_snoop::QmiMessage qmi_msg;\n uint32_t current_length =\n std::min(static_cast(snoop_data_len), sizeof(qmi_msg.opaque_bytes));\n qmi_msg.is_partial_copy = snoop_data_len > current_length;\n qmi_msg.direction = direction;\n qmi_msg.timestamp = zx_clock_get_monotonic();\n memcpy(qmi_msg.opaque_bytes.data_, snoop_data, current_length);\n snoop_msg.set_qmi_message(&qmi_msg);\n zxlogf(INFO, \"qmi-fake-transport: snoop msg %u %u %u %u sent\\n\", qmi_msg.opaque_bytes.data_[0],\n qmi_msg.opaque_bytes.data_[1], qmi_msg.opaque_bytes.data_[2],\n qmi_msg.opaque_bytes.data_[3]);\n fidl_tel_snoop::Publisher::Call::SendMessage(zx::unowned_channel(GetCtrlSnoopChannel().get()),\n snoop_msg);\n }\n}\n\nvoid QmiDevice::ReplyCtrlMsg(uint8_t* req, uint32_t req_size, uint8_t* resp, uint32_t resp_size) {\n memset(resp, 170, resp_size);\n if (0 == memcmp(req, kQmiInitReq, sizeof(kQmiInitReq))) {\n memcpy(resp, kQmiPerioEvent,\n std::min(sizeof(kQmiPerioEvent), static_cast(resp_size)));\n sent_fake_qmi_msg(GetCtrlChannel(), resp, resp_size);\n SnoopCtrlMsg(resp, resp_size, fidl_tel_snoop::Direction::FROM_MODEM);\n memcpy(resp, kQmiInitResp, std::min(sizeof(kQmiInitResp), static_cast(resp_size)));\n sent_fake_qmi_msg(GetCtrlChannel(), resp, resp_size);\n SnoopCtrlMsg(resp, resp_size, fidl_tel_snoop::Direction::FROM_MODEM);\n } else if (0 == memcmp(req, kQmiImeiReq, sizeof(kQmiImeiReq))) {\n memcpy(resp, kQmiImeiResp, std::min(sizeof(kQmiImeiResp), static_cast(resp_size)));\n sent_fake_qmi_msg(GetCtrlChannel(), resp, resp_size);\n SnoopCtrlMsg(resp, resp_size, fidl_tel_snoop::Direction::FROM_MODEM);\n memcpy(resp, kQmiPerioEvent,\n std::min(sizeof(kQmiPerioEvent), static_cast(resp_size)));\n sent_fake_qmi_msg(GetCtrlChannel(), resp, resp_size);\n SnoopCtrlMsg(resp, resp_size, fidl_tel_snoop::Direction::FROM_MODEM);\n } else {\n zxlogf(ERROR, \"qmi-fake-driver: unexpected qmi msg received\\n\");\n memcpy(resp, kQmiNonsenseResp,\n std::min(sizeof(kQmiNonsenseResp), static_cast(resp_size)));\n sent_fake_qmi_msg(GetCtrlChannel(), resp, resp_size);\n SnoopCtrlMsg(resp, resp_size, fidl_tel_snoop::Direction::FROM_MODEM);\n }\n}\n\nstatic int qmi_fake_transport_thread(void* cookie) {\n assert(cookie != NULL);\n QmiDevice* device_ptr = static_cast(cookie);\n uint32_t req_len = 0;\n uint8_t req_buf[kTelCtrlPlanePktMax];\n uint8_t resp_buf[kTelCtrlPlanePktMax];\n\n zx_port_packet_t packet;\n zxlogf(INFO, \"qmi-fake-transport: event loop initialized\\n\");\n while (true) {\n zx_status_t status = device_ptr->GetCtrlChannelPort().wait(zx::time::infinite(), &packet);\n if (status == ZX_ERR_TIMED_OUT) {\n zxlogf(ERROR, \"qmi-fake-transport: timed out: %s\\n\", zx_status_get_string(status));\n } else if (status == ZX_OK) {\n switch (packet.key) {\n case tel_fake::kChannelMsg:\n if (packet.signal.observed & ZX_CHANNEL_PEER_CLOSED) {\n zxlogf(ERROR, \"qmi-fake-transport: channel closed\\n\");\n status = device_ptr->CloseCtrlChannel();\n continue;\n }\n status = device_ptr->GetCtrlChannel().read(0, req_buf, NULL, kTelCtrlPlanePktMax, 0,\n &req_len, NULL);\n if (status != ZX_OK) {\n zxlogf(ERROR, \"qmi-fake-transport: failed to read channel: %s\\n\",\n zx_status_get_string(status));\n return status;\n }\n device_ptr->SnoopCtrlMsg(req_buf, kTelCtrlPlanePktMax,\n fidl_tel_snoop::Direction::TO_MODEM);\n \/\/ TODO (jiamingw): parse QMI msg, form reply and write back to channel.\n device_ptr->ReplyCtrlMsg(req_buf, req_len, resp_buf, kTelCtrlPlanePktMax);\n status = device_ptr->SetAsyncWait();\n if (status != ZX_OK) {\n return status;\n }\n break;\n case tel_fake::kTerminateMsg:\n device_ptr->EventLoopCleanup();\n return 0;\n default:\n zxlogf(ERROR, \"qmi-fake-transport: qmi_port undefined key %lu\\n\", packet.key);\n assert(0);\n }\n } else {\n zxlogf(ERROR, \"qmi-fake-transport: qmi_port err %d\\n\", status);\n assert(0);\n }\n }\n return 0;\n}\n\nzx_status_t QmiDevice::Bind() {\n \/\/ create a port to watch qmi messages\n zx_status_t status = zx::port::create(0, &GetCtrlChannelPort());\n if (status != ZX_OK) {\n zxlogf(ERROR, \"qmi-fake-transport: failed to create a port: %s\\n\",\n zx_status_get_string(status));\n return status;\n }\n\n \/\/ create the handler thread\n GetCtrlThrd() = std::thread(qmi_fake_transport_thread, this);\n\n device_add_args_t args = {};\n args.version = DEVICE_ADD_ARGS_VERSION;\n args.name = \"qmi-fake\";\n args.ctx = this;\n args.ops = &qmi_fake_device_ops;\n args.proto_id = ZX_PROTOCOL_QMI_TRANSPORT;\n status = device_add(GetParentDevice(), &args, &GetTelDevPtr());\n if (status != ZX_OK) {\n zxlogf(ERROR, \"qmi-fake-transport: could not add device: %d\\n\", status);\n zx_port_packet_t packet = {};\n packet.key = tel_fake::kTerminateMsg;\n GetCtrlChannelPort().queue(&packet);\n zxlogf(INFO, \"qmi-fake-transport: joining thread\\n\");\n GetCtrlThrd().join();\n return status;\n }\n return status;\n}\n\n} \/\/ namespace qmi_fake\n","avg_line_length":41.6684210526,"max_line_length":100,"alphanum_fraction":0.6501199949} {"size":1880,"ext":"hpp","lang":"C++","max_stars_count":null,"content":"\/*\n * Copyright (c) 2012, Dennis Hedback\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef DESCARTIFY_COMMON_HPP\n#define DESCARTIFY_COMMON_HPP\n\n#include \n#include \n#include \n\ntypedef std::set Set;\ntypedef std::vector Tuple;\ntypedef std::vector Generator;\n\n#ifdef USE_HTAB\n #include \n typedef boost::unordered_set Product;\n#else\n typedef std::set Product;\n#endif \/\/ USE_HTAB\n\nstruct Options\n{\n};\n\nvoid cartesian_product(Generator &, Product &, bool);\n\n#endif \/\/ DESCARTIFY_COMMON_HPP\n","avg_line_length":36.1538461538,"max_line_length":78,"alphanum_fraction":0.7590425532} {"size":18967,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/**\n\t* \\file VecBrlyVCall.cpp\n\t* vector VecBrlyVCall (implementation)\n\t* \\copyright (C) 2016-2020 MPSI Technologies GmbH\n\t* \\author Alexander Wirthmueller (auto-generation)\n\t* \\date created: 11 Jan 2021\n *\/\n\/\/ IP header --- ABOVE\n\n#include \"VecBrlyVCall.h\"\n\nusing namespace std;\nusing namespace Sbecore;\nusing namespace Xmlio;\n\n\/******************************************************************************\n namespace VecBrlyVCall\n ******************************************************************************\/\n\nuint VecBrlyVCall::getIx(\n\t\t\tconst string& sref\n\t\t) {\n\tstring s = StrMod::lc(sref);\n\n\tif (s == \"callbrlyboolvalpreset\") return CALLBRLYBOOLVALPRESET;\n\tif (s == \"callbrlyclaimchg\") return CALLBRLYCLAIMCHG;\n\tif (s == \"callbrlycon.flteq\") return CALLBRLYCON_FLTEQ;\n\tif (s == \"callbrlycon.ttbeq\") return CALLBRLYCON_TTBEQ;\n\tif (s == \"callbrlyconmod\") return CALLBRLYCONMOD;\n\tif (s == \"callbrlyconmod.coreq\") return CALLBRLYCONMOD_COREQ;\n\tif (s == \"callbrlyconmod.flteq\") return CALLBRLYCONMOD_FLTEQ;\n\tif (s == \"callbrlyconreqpmod.coneq\") return CALLBRLYCONREQPMOD_CONEQ;\n\tif (s == \"callbrlyconreqpmod.eqpeq\") return CALLBRLYCONREQPMOD_EQPEQ;\n\tif (s == \"callbrlyconrfltmod.coneq\") return CALLBRLYCONRFLTMOD_CONEQ;\n\tif (s == \"callbrlyconrfltmod.flteq\") return CALLBRLYCONRFLTMOD_FLTEQ;\n\tif (s == \"callbrlyconrsegmod.coneq\") return CALLBRLYCONRSEGMOD_CONEQ;\n\tif (s == \"callbrlyconrsegmod.segeq\") return CALLBRLYCONRSEGMOD_SEGEQ;\n\tif (s == \"callbrlyconupd.refeq\") return CALLBRLYCONUPD_REFEQ;\n\tif (s == \"callbrlycrdactive\") return CALLBRLYCRDACTIVE;\n\tif (s == \"callbrlycrdclose\") return CALLBRLYCRDCLOSE;\n\tif (s == \"callbrlycrdopen\") return CALLBRLYCRDOPEN;\n\tif (s == \"callbrlyctlaparmod.usreq\") return CALLBRLYCTLAPARMOD_USREQ;\n\tif (s == \"callbrlydatchg\") return CALLBRLYDATCHG;\n\tif (s == \"callbrlydblvalpreset\") return CALLBRLYDBLVALPRESET;\n\tif (s == \"callbrlydlgclose\") return CALLBRLYDLGCLOSE;\n\tif (s == \"callbrlyeqp.hkteq\") return CALLBRLYEQP_HKTEQ;\n\tif (s == \"callbrlyeqp.insbs\") return CALLBRLYEQP_INSBS;\n\tif (s == \"callbrlyeqp.opreq\") return CALLBRLYEQP_OPREQ;\n\tif (s == \"callbrlyeqp.ptyeq\") return CALLBRLYEQP_PTYEQ;\n\tif (s == \"callbrlyeqpmod\") return CALLBRLYEQPMOD;\n\tif (s == \"callbrlyeqpmod.hkthkueq\") return CALLBRLYEQPMOD_HKTHKUEQ;\n\tif (s == \"callbrlyeqpmod.opreq\") return CALLBRLYEQPMOD_OPREQ;\n\tif (s == \"callbrlyeqpmod.ptyeq\") return CALLBRLYEQPMOD_PTYEQ;\n\tif (s == \"callbrlyeqpupd.refeq\") return CALLBRLYEQPUPD_REFEQ;\n\tif (s == \"callbrlyfafawptmod.fafeq\") return CALLBRLYFAFAWPTMOD_FAFEQ;\n\tif (s == \"callbrlyfafmod\") return CALLBRLYFAFMOD;\n\tif (s == \"callbrlyfafupd.refeq\") return CALLBRLYFAFUPD_REFEQ;\n\tif (s == \"callbrlyfil.clueq\") return CALLBRLYFIL_CLUEQ;\n\tif (s == \"callbrlyfil.reteq\") return CALLBRLYFIL_RETEQ;\n\tif (s == \"callbrlyfil.reueq\") return CALLBRLYFIL_REUEQ;\n\tif (s == \"callbrlyfilmod\") return CALLBRLYFILMOD;\n\tif (s == \"callbrlyfilmod.clueq\") return CALLBRLYFILMOD_CLUEQ;\n\tif (s == \"callbrlyfilmod.retreueq\") return CALLBRLYFILMOD_RETREUEQ;\n\tif (s == \"callbrlyfilupd.refeq\") return CALLBRLYFILUPD_REFEQ;\n\tif (s == \"callbrlyflt.eqpeq\") return CALLBRLYFLT_EQPEQ;\n\tif (s == \"callbrlyflt.fafeq\") return CALLBRLYFLT_FAFEQ;\n\tif (s == \"callbrlyflt.ttbeq\") return CALLBRLYFLT_TTBEQ;\n\tif (s == \"callbrlyfltmod\") return CALLBRLYFLTMOD;\n\tif (s == \"callbrlyfltmod.legeq\") return CALLBRLYFLTMOD_LEGEQ;\n\tif (s == \"callbrlyfltmod.ttbeq\") return CALLBRLYFLTMOD_TTBEQ;\n\tif (s == \"callbrlyfltrfltmod.dfleq\") return CALLBRLYFLTRFLTMOD_DFLEQ;\n\tif (s == \"callbrlyfltrfltmod.ofleq\") return CALLBRLYFLTRFLTMOD_OFLEQ;\n\tif (s == \"callbrlyfltrlocmod.flteq\") return CALLBRLYFLTRLOCMOD_FLTEQ;\n\tif (s == \"callbrlyfltrlocmod.loceq\") return CALLBRLYFLTRLOCMOD_LOCEQ;\n\tif (s == \"callbrlyfltupd.refeq\") return CALLBRLYFLTUPD_REFEQ;\n\tif (s == \"callbrlyhusrrunvmod.crdusreq\") return CALLBRLYHUSRRUNVMOD_CRDUSREQ;\n\tif (s == \"callbrlyintvalpreset\") return CALLBRLYINTVALPRESET;\n\tif (s == \"callbrlyixpreset\") return CALLBRLYIXPRESET;\n\tif (s == \"callbrlyklkjkeymod.klsakeyeq\") return CALLBRLYKLKJKEYMOD_KLSAKEYEQ;\n\tif (s == \"callbrlyklsakeymod.klseq\") return CALLBRLYKLSAKEYMOD_KLSEQ;\n\tif (s == \"callbrlyklsakeymod.klsmtburfeq\") return CALLBRLYKLSAKEYMOD_KLSMTBURFEQ;\n\tif (s == \"callbrlyleg.clueq\") return CALLBRLYLEG_CLUEQ;\n\tif (s == \"callbrlyleg.insbs\") return CALLBRLYLEG_INSBS;\n\tif (s == \"callbrlyleg.typeq\") return CALLBRLYLEG_TYPEQ;\n\tif (s == \"callbrlylegmod\") return CALLBRLYLEGMOD;\n\tif (s == \"callbrlylegmod.bloeq\") return CALLBRLYLEGMOD_BLOEQ;\n\tif (s == \"callbrlylegmod.clueq\") return CALLBRLYLEGMOD_CLUEQ;\n\tif (s == \"callbrlylegmod.eloeq\") return CALLBRLYLEGMOD_ELOEQ;\n\tif (s == \"callbrlylegrlegmod.dlgeq\") return CALLBRLYLEGRLEGMOD_DLGEQ;\n\tif (s == \"callbrlylegrlegmod.olgeq\") return CALLBRLYLEGRLEGMOD_OLGEQ;\n\tif (s == \"callbrlylegrlocmod.legeq\") return CALLBRLYLEGRLOCMOD_LEGEQ;\n\tif (s == \"callbrlylegrlocmod.loceq\") return CALLBRLYLEGRLOCMOD_LOCEQ;\n\tif (s == \"callbrlylegupd.refeq\") return CALLBRLYLEGUPD_REFEQ;\n\tif (s == \"callbrlyloc.eqpeq\") return CALLBRLYLOC_EQPEQ;\n\tif (s == \"callbrlyloc.insbs\") return CALLBRLYLOC_INSBS;\n\tif (s == \"callbrlyloc.typeq\") return CALLBRLYLOC_TYPEQ;\n\tif (s == \"callbrlylocmod\") return CALLBRLYLOCMOD;\n\tif (s == \"callbrlylocmod.regeq\") return CALLBRLYLOCMOD_REGEQ;\n\tif (s == \"callbrlylocrsegmod.loceq\") return CALLBRLYLOCRSEGMOD_LOCEQ;\n\tif (s == \"callbrlylocrsegmod.segeq\") return CALLBRLYLOCRSEGMOD_SEGEQ;\n\tif (s == \"callbrlylocupd.refeq\") return CALLBRLYLOCUPD_REFEQ;\n\tif (s == \"callbrlylog\") return CALLBRLYLOG;\n\tif (s == \"callbrlylogout\") return CALLBRLYLOGOUT;\n\tif (s == \"callbrlymonstatchg\") return CALLBRLYMONSTATCHG;\n\tif (s == \"callbrlyndemod\") return CALLBRLYNDEMOD;\n\tif (s == \"callbrlyndemod.eqpeq\") return CALLBRLYNDEMOD_EQPEQ;\n\tif (s == \"callbrlyndemod.rlyeq\") return CALLBRLYNDEMOD_RLYEQ;\n\tif (s == \"callbrlyndemod.supeq\") return CALLBRLYNDEMOD_SUPEQ;\n\tif (s == \"callbrlyndeupd.refeq\") return CALLBRLYNDEUPD_REFEQ;\n\tif (s == \"callbrlynodechg\") return CALLBRLYNODECHG;\n\tif (s == \"callbrlyoprmod\") return CALLBRLYOPRMOD;\n\tif (s == \"callbrlyoprupd.refeq\") return CALLBRLYOPRUPD_REFEQ;\n\tif (s == \"callbrlyplocrlocmod.dloeq\") return CALLBRLYPLOCRLOCMOD_DLOEQ;\n\tif (s == \"callbrlyplocrlocmod.oloeq\") return CALLBRLYPLOCRLOCMOD_OLOEQ;\n\tif (s == \"callbrlyprsadetmod.prseq\") return CALLBRLYPRSADETMOD_PRSEQ;\n\tif (s == \"callbrlyprsjlnmmod.prseq\") return CALLBRLYPRSJLNMMOD_PRSEQ;\n\tif (s == \"callbrlyprsmod\") return CALLBRLYPRSMOD;\n\tif (s == \"callbrlyprsupd.refeq\") return CALLBRLYPRSUPD_REFEQ;\n\tif (s == \"callbrlyptymod\") return CALLBRLYPTYMOD;\n\tif (s == \"callbrlyptyupd.refeq\") return CALLBRLYPTYUPD_REFEQ;\n\tif (s == \"callbrlyrecaccess\") return CALLBRLYRECACCESS;\n\tif (s == \"callbrlyrefpreset\") return CALLBRLYREFPRESET;\n\tif (s == \"callbrlyrefspreset\") return CALLBRLYREFSPRESET;\n\tif (s == \"callbrlyreg.insbs\") return CALLBRLYREG_INSBS;\n\tif (s == \"callbrlyreg.isleaf\") return CALLBRLYREG_ISLEAF;\n\tif (s == \"callbrlyreg.supeq\") return CALLBRLYREG_SUPEQ;\n\tif (s == \"callbrlyregadssmod.regeq\") return CALLBRLYREGADSSMOD_REGEQ;\n\tif (s == \"callbrlyregjmod.regeq\") return CALLBRLYREGJMOD_REGEQ;\n\tif (s == \"callbrlyregjtitmod.regeq\") return CALLBRLYREGJTITMOD_REGEQ;\n\tif (s == \"callbrlyregmod\") return CALLBRLYREGMOD;\n\tif (s == \"callbrlyregmod.supeq\") return CALLBRLYREGMOD_SUPEQ;\n\tif (s == \"callbrlyregupd.refeq\") return CALLBRLYREGUPD_REFEQ;\n\tif (s == \"callbrlyrly.coneq\") return CALLBRLYRLY_CONEQ;\n\tif (s == \"callbrlyrlymod\") return CALLBRLYRLYMOD;\n\tif (s == \"callbrlyrlymod.coneq\") return CALLBRLYRLYMOD_CONEQ;\n\tif (s == \"callbrlyrlyupd.refeq\") return CALLBRLYRLYUPD_REFEQ;\n\tif (s == \"callbrlyseg.reteq\") return CALLBRLYSEG_RETEQ;\n\tif (s == \"callbrlyseg.reueq\") return CALLBRLYSEG_REUEQ;\n\tif (s == \"callbrlysegmod\") return CALLBRLYSEGMOD;\n\tif (s == \"callbrlysegmod.retreueq\") return CALLBRLYSEGMOD_RETREUEQ;\n\tif (s == \"callbrlysegrsegmod.dsgeq\") return CALLBRLYSEGRSEGMOD_DSGEQ;\n\tif (s == \"callbrlysegrsegmod.osgeq\") return CALLBRLYSEGRSEGMOD_OSGEQ;\n\tif (s == \"callbrlysegupd.refeq\") return CALLBRLYSEGUPD_REFEQ;\n\tif (s == \"callbrlysesmod\") return CALLBRLYSESMOD;\n\tif (s == \"callbrlysesmod.usreq\") return CALLBRLYSESMOD_USREQ;\n\tif (s == \"callbrlysesupd.refeq\") return CALLBRLYSESUPD_REFEQ;\n\tif (s == \"callbrlysgechg\") return CALLBRLYSGECHG;\n\tif (s == \"callbrlyshrdatchg\") return CALLBRLYSHRDATCHG;\n\tif (s == \"callbrlysrefpreset\") return CALLBRLYSREFPRESET;\n\tif (s == \"callbrlystatchg\") return CALLBRLYSTATCHG;\n\tif (s == \"callbrlystgchg\") return CALLBRLYSTGCHG;\n\tif (s == \"callbrlystubchg\") return CALLBRLYSTUBCHG;\n\tif (s == \"callbrlysuspsess\") return CALLBRLYSUSPSESS;\n\tif (s == \"callbrlyttb.fileq\") return CALLBRLYTTB_FILEQ;\n\tif (s == \"callbrlyttbmod\") return CALLBRLYTTBMOD;\n\tif (s == \"callbrlyttbupd.refeq\") return CALLBRLYTTBUPD_REFEQ;\n\tif (s == \"callbrlytxtvalpreset\") return CALLBRLYTXTVALPRESET;\n\tif (s == \"callbrlyusgaaccmod.usgeq\") return CALLBRLYUSGAACCMOD_USGEQ;\n\tif (s == \"callbrlyusgmod\") return CALLBRLYUSGMOD;\n\tif (s == \"callbrlyusgupd.refeq\") return CALLBRLYUSGUPD_REFEQ;\n\tif (s == \"callbrlyusr.prseq\") return CALLBRLYUSR_PRSEQ;\n\tif (s == \"callbrlyusr.usgeq\") return CALLBRLYUSR_USGEQ;\n\tif (s == \"callbrlyusraaccmod.usreq\") return CALLBRLYUSRAACCMOD_USREQ;\n\tif (s == \"callbrlyusrjstemod.usreq\") return CALLBRLYUSRJSTEMOD_USREQ;\n\tif (s == \"callbrlyusrmod\") return CALLBRLYUSRMOD;\n\tif (s == \"callbrlyusrrusgmod.usgeq\") return CALLBRLYUSRRUSGMOD_USGEQ;\n\tif (s == \"callbrlyusrrusgmod.usreq\") return CALLBRLYUSRRUSGMOD_USREQ;\n\tif (s == \"callbrlyusrupd.refeq\") return CALLBRLYUSRUPD_REFEQ;\n\tif (s == \"callbrlyvlocrlocmod.dloeq\") return CALLBRLYVLOCRLOCMOD_DLOEQ;\n\tif (s == \"callbrlyvlocrlocmod.oloeq\") return CALLBRLYVLOCRLOCMOD_OLOEQ;\n\n\treturn(0);\n};\n\nstring VecBrlyVCall::getSref(\n\t\t\tconst uint ix\n\t\t) {\n\tif (ix == CALLBRLYBOOLVALPRESET) return(\"CallBrlyBoolvalPreSet\");\n\tif (ix == CALLBRLYCLAIMCHG) return(\"CallBrlyClaimChg\");\n\tif (ix == CALLBRLYCON_FLTEQ) return(\"CallBrlyCon.fltEq\");\n\tif (ix == CALLBRLYCON_TTBEQ) return(\"CallBrlyCon.ttbEq\");\n\tif (ix == CALLBRLYCONMOD) return(\"CallBrlyConMod\");\n\tif (ix == CALLBRLYCONMOD_COREQ) return(\"CallBrlyConMod.corEq\");\n\tif (ix == CALLBRLYCONMOD_FLTEQ) return(\"CallBrlyConMod.fltEq\");\n\tif (ix == CALLBRLYCONREQPMOD_CONEQ) return(\"CallBrlyConReqpMod.conEq\");\n\tif (ix == CALLBRLYCONREQPMOD_EQPEQ) return(\"CallBrlyConReqpMod.eqpEq\");\n\tif (ix == CALLBRLYCONRFLTMOD_CONEQ) return(\"CallBrlyConRfltMod.conEq\");\n\tif (ix == CALLBRLYCONRFLTMOD_FLTEQ) return(\"CallBrlyConRfltMod.fltEq\");\n\tif (ix == CALLBRLYCONRSEGMOD_CONEQ) return(\"CallBrlyConRsegMod.conEq\");\n\tif (ix == CALLBRLYCONRSEGMOD_SEGEQ) return(\"CallBrlyConRsegMod.segEq\");\n\tif (ix == CALLBRLYCONUPD_REFEQ) return(\"CallBrlyConUpd.refEq\");\n\tif (ix == CALLBRLYCRDACTIVE) return(\"CallBrlyCrdActive\");\n\tif (ix == CALLBRLYCRDCLOSE) return(\"CallBrlyCrdClose\");\n\tif (ix == CALLBRLYCRDOPEN) return(\"CallBrlyCrdOpen\");\n\tif (ix == CALLBRLYCTLAPARMOD_USREQ) return(\"CallBrlyCtlAparMod.usrEq\");\n\tif (ix == CALLBRLYDATCHG) return(\"CallBrlyDatChg\");\n\tif (ix == CALLBRLYDBLVALPRESET) return(\"CallBrlyDblvalPreSet\");\n\tif (ix == CALLBRLYDLGCLOSE) return(\"CallBrlyDlgClose\");\n\tif (ix == CALLBRLYEQP_HKTEQ) return(\"CallBrlyEqp.hktEq\");\n\tif (ix == CALLBRLYEQP_INSBS) return(\"CallBrlyEqp.inSbs\");\n\tif (ix == CALLBRLYEQP_OPREQ) return(\"CallBrlyEqp.oprEq\");\n\tif (ix == CALLBRLYEQP_PTYEQ) return(\"CallBrlyEqp.ptyEq\");\n\tif (ix == CALLBRLYEQPMOD) return(\"CallBrlyEqpMod\");\n\tif (ix == CALLBRLYEQPMOD_HKTHKUEQ) return(\"CallBrlyEqpMod.hktHkuEq\");\n\tif (ix == CALLBRLYEQPMOD_OPREQ) return(\"CallBrlyEqpMod.oprEq\");\n\tif (ix == CALLBRLYEQPMOD_PTYEQ) return(\"CallBrlyEqpMod.ptyEq\");\n\tif (ix == CALLBRLYEQPUPD_REFEQ) return(\"CallBrlyEqpUpd.refEq\");\n\tif (ix == CALLBRLYFAFAWPTMOD_FAFEQ) return(\"CallBrlyFafAwptMod.fafEq\");\n\tif (ix == CALLBRLYFAFMOD) return(\"CallBrlyFafMod\");\n\tif (ix == CALLBRLYFAFUPD_REFEQ) return(\"CallBrlyFafUpd.refEq\");\n\tif (ix == CALLBRLYFIL_CLUEQ) return(\"CallBrlyFil.cluEq\");\n\tif (ix == CALLBRLYFIL_RETEQ) return(\"CallBrlyFil.retEq\");\n\tif (ix == CALLBRLYFIL_REUEQ) return(\"CallBrlyFil.reuEq\");\n\tif (ix == CALLBRLYFILMOD) return(\"CallBrlyFilMod\");\n\tif (ix == CALLBRLYFILMOD_CLUEQ) return(\"CallBrlyFilMod.cluEq\");\n\tif (ix == CALLBRLYFILMOD_RETREUEQ) return(\"CallBrlyFilMod.retReuEq\");\n\tif (ix == CALLBRLYFILUPD_REFEQ) return(\"CallBrlyFilUpd.refEq\");\n\tif (ix == CALLBRLYFLT_EQPEQ) return(\"CallBrlyFlt.eqpEq\");\n\tif (ix == CALLBRLYFLT_FAFEQ) return(\"CallBrlyFlt.fafEq\");\n\tif (ix == CALLBRLYFLT_TTBEQ) return(\"CallBrlyFlt.ttbEq\");\n\tif (ix == CALLBRLYFLTMOD) return(\"CallBrlyFltMod\");\n\tif (ix == CALLBRLYFLTMOD_LEGEQ) return(\"CallBrlyFltMod.legEq\");\n\tif (ix == CALLBRLYFLTMOD_TTBEQ) return(\"CallBrlyFltMod.ttbEq\");\n\tif (ix == CALLBRLYFLTRFLTMOD_DFLEQ) return(\"CallBrlyFltRfltMod.dflEq\");\n\tif (ix == CALLBRLYFLTRFLTMOD_OFLEQ) return(\"CallBrlyFltRfltMod.oflEq\");\n\tif (ix == CALLBRLYFLTRLOCMOD_FLTEQ) return(\"CallBrlyFltRlocMod.fltEq\");\n\tif (ix == CALLBRLYFLTRLOCMOD_LOCEQ) return(\"CallBrlyFltRlocMod.locEq\");\n\tif (ix == CALLBRLYFLTUPD_REFEQ) return(\"CallBrlyFltUpd.refEq\");\n\tif (ix == CALLBRLYHUSRRUNVMOD_CRDUSREQ) return(\"CallBrlyHusrRunvMod.crdUsrEq\");\n\tif (ix == CALLBRLYINTVALPRESET) return(\"CallBrlyIntvalPreSet\");\n\tif (ix == CALLBRLYIXPRESET) return(\"CallBrlyIxPreSet\");\n\tif (ix == CALLBRLYKLKJKEYMOD_KLSAKEYEQ) return(\"CallBrlyKlkJkeyMod.klsAkeyEq\");\n\tif (ix == CALLBRLYKLSAKEYMOD_KLSEQ) return(\"CallBrlyKlsAkeyMod.klsEq\");\n\tif (ix == CALLBRLYKLSAKEYMOD_KLSMTBURFEQ) return(\"CallBrlyKlsAkeyMod.klsMtbUrfEq\");\n\tif (ix == CALLBRLYLEG_CLUEQ) return(\"CallBrlyLeg.cluEq\");\n\tif (ix == CALLBRLYLEG_INSBS) return(\"CallBrlyLeg.inSbs\");\n\tif (ix == CALLBRLYLEG_TYPEQ) return(\"CallBrlyLeg.typEq\");\n\tif (ix == CALLBRLYLEGMOD) return(\"CallBrlyLegMod\");\n\tif (ix == CALLBRLYLEGMOD_BLOEQ) return(\"CallBrlyLegMod.bloEq\");\n\tif (ix == CALLBRLYLEGMOD_CLUEQ) return(\"CallBrlyLegMod.cluEq\");\n\tif (ix == CALLBRLYLEGMOD_ELOEQ) return(\"CallBrlyLegMod.eloEq\");\n\tif (ix == CALLBRLYLEGRLEGMOD_DLGEQ) return(\"CallBrlyLegRlegMod.dlgEq\");\n\tif (ix == CALLBRLYLEGRLEGMOD_OLGEQ) return(\"CallBrlyLegRlegMod.olgEq\");\n\tif (ix == CALLBRLYLEGRLOCMOD_LEGEQ) return(\"CallBrlyLegRlocMod.legEq\");\n\tif (ix == CALLBRLYLEGRLOCMOD_LOCEQ) return(\"CallBrlyLegRlocMod.locEq\");\n\tif (ix == CALLBRLYLEGUPD_REFEQ) return(\"CallBrlyLegUpd.refEq\");\n\tif (ix == CALLBRLYLOC_EQPEQ) return(\"CallBrlyLoc.eqpEq\");\n\tif (ix == CALLBRLYLOC_INSBS) return(\"CallBrlyLoc.inSbs\");\n\tif (ix == CALLBRLYLOC_TYPEQ) return(\"CallBrlyLoc.typEq\");\n\tif (ix == CALLBRLYLOCMOD) return(\"CallBrlyLocMod\");\n\tif (ix == CALLBRLYLOCMOD_REGEQ) return(\"CallBrlyLocMod.regEq\");\n\tif (ix == CALLBRLYLOCRSEGMOD_LOCEQ) return(\"CallBrlyLocRsegMod.locEq\");\n\tif (ix == CALLBRLYLOCRSEGMOD_SEGEQ) return(\"CallBrlyLocRsegMod.segEq\");\n\tif (ix == CALLBRLYLOCUPD_REFEQ) return(\"CallBrlyLocUpd.refEq\");\n\tif (ix == CALLBRLYLOG) return(\"CallBrlyLog\");\n\tif (ix == CALLBRLYLOGOUT) return(\"CallBrlyLogout\");\n\tif (ix == CALLBRLYMONSTATCHG) return(\"CallBrlyMonstatChg\");\n\tif (ix == CALLBRLYNDEMOD) return(\"CallBrlyNdeMod\");\n\tif (ix == CALLBRLYNDEMOD_EQPEQ) return(\"CallBrlyNdeMod.eqpEq\");\n\tif (ix == CALLBRLYNDEMOD_RLYEQ) return(\"CallBrlyNdeMod.rlyEq\");\n\tif (ix == CALLBRLYNDEMOD_SUPEQ) return(\"CallBrlyNdeMod.supEq\");\n\tif (ix == CALLBRLYNDEUPD_REFEQ) return(\"CallBrlyNdeUpd.refEq\");\n\tif (ix == CALLBRLYNODECHG) return(\"CallBrlyNodeChg\");\n\tif (ix == CALLBRLYOPRMOD) return(\"CallBrlyOprMod\");\n\tif (ix == CALLBRLYOPRUPD_REFEQ) return(\"CallBrlyOprUpd.refEq\");\n\tif (ix == CALLBRLYPLOCRLOCMOD_DLOEQ) return(\"CallBrlyPlocRlocMod.dloEq\");\n\tif (ix == CALLBRLYPLOCRLOCMOD_OLOEQ) return(\"CallBrlyPlocRlocMod.oloEq\");\n\tif (ix == CALLBRLYPRSADETMOD_PRSEQ) return(\"CallBrlyPrsAdetMod.prsEq\");\n\tif (ix == CALLBRLYPRSJLNMMOD_PRSEQ) return(\"CallBrlyPrsJlnmMod.prsEq\");\n\tif (ix == CALLBRLYPRSMOD) return(\"CallBrlyPrsMod\");\n\tif (ix == CALLBRLYPRSUPD_REFEQ) return(\"CallBrlyPrsUpd.refEq\");\n\tif (ix == CALLBRLYPTYMOD) return(\"CallBrlyPtyMod\");\n\tif (ix == CALLBRLYPTYUPD_REFEQ) return(\"CallBrlyPtyUpd.refEq\");\n\tif (ix == CALLBRLYRECACCESS) return(\"CallBrlyRecaccess\");\n\tif (ix == CALLBRLYREFPRESET) return(\"CallBrlyRefPreSet\");\n\tif (ix == CALLBRLYREFSPRESET) return(\"CallBrlyRefsPreSet\");\n\tif (ix == CALLBRLYREG_INSBS) return(\"CallBrlyReg.inSbs\");\n\tif (ix == CALLBRLYREG_ISLEAF) return(\"CallBrlyReg.isLeaf\");\n\tif (ix == CALLBRLYREG_SUPEQ) return(\"CallBrlyReg.supEq\");\n\tif (ix == CALLBRLYREGADSSMOD_REGEQ) return(\"CallBrlyRegAdssMod.regEq\");\n\tif (ix == CALLBRLYREGJMOD_REGEQ) return(\"CallBrlyRegJMod.regEq\");\n\tif (ix == CALLBRLYREGJTITMOD_REGEQ) return(\"CallBrlyRegJtitMod.regEq\");\n\tif (ix == CALLBRLYREGMOD) return(\"CallBrlyRegMod\");\n\tif (ix == CALLBRLYREGMOD_SUPEQ) return(\"CallBrlyRegMod.supEq\");\n\tif (ix == CALLBRLYREGUPD_REFEQ) return(\"CallBrlyRegUpd.refEq\");\n\tif (ix == CALLBRLYRLY_CONEQ) return(\"CallBrlyRly.conEq\");\n\tif (ix == CALLBRLYRLYMOD) return(\"CallBrlyRlyMod\");\n\tif (ix == CALLBRLYRLYMOD_CONEQ) return(\"CallBrlyRlyMod.conEq\");\n\tif (ix == CALLBRLYRLYUPD_REFEQ) return(\"CallBrlyRlyUpd.refEq\");\n\tif (ix == CALLBRLYSEG_RETEQ) return(\"CallBrlySeg.retEq\");\n\tif (ix == CALLBRLYSEG_REUEQ) return(\"CallBrlySeg.reuEq\");\n\tif (ix == CALLBRLYSEGMOD) return(\"CallBrlySegMod\");\n\tif (ix == CALLBRLYSEGMOD_RETREUEQ) return(\"CallBrlySegMod.retReuEq\");\n\tif (ix == CALLBRLYSEGRSEGMOD_DSGEQ) return(\"CallBrlySegRsegMod.dsgEq\");\n\tif (ix == CALLBRLYSEGRSEGMOD_OSGEQ) return(\"CallBrlySegRsegMod.osgEq\");\n\tif (ix == CALLBRLYSEGUPD_REFEQ) return(\"CallBrlySegUpd.refEq\");\n\tif (ix == CALLBRLYSESMOD) return(\"CallBrlySesMod\");\n\tif (ix == CALLBRLYSESMOD_USREQ) return(\"CallBrlySesMod.usrEq\");\n\tif (ix == CALLBRLYSESUPD_REFEQ) return(\"CallBrlySesUpd.refEq\");\n\tif (ix == CALLBRLYSGECHG) return(\"CallBrlySgeChg\");\n\tif (ix == CALLBRLYSHRDATCHG) return(\"CallBrlyShrdatChg\");\n\tif (ix == CALLBRLYSREFPRESET) return(\"CallBrlySrefPreSet\");\n\tif (ix == CALLBRLYSTATCHG) return(\"CallBrlyStatChg\");\n\tif (ix == CALLBRLYSTGCHG) return(\"CallBrlyStgChg\");\n\tif (ix == CALLBRLYSTUBCHG) return(\"CallBrlyStubChg\");\n\tif (ix == CALLBRLYSUSPSESS) return(\"CallBrlySuspsess\");\n\tif (ix == CALLBRLYTTB_FILEQ) return(\"CallBrlyTtb.filEq\");\n\tif (ix == CALLBRLYTTBMOD) return(\"CallBrlyTtbMod\");\n\tif (ix == CALLBRLYTTBUPD_REFEQ) return(\"CallBrlyTtbUpd.refEq\");\n\tif (ix == CALLBRLYTXTVALPRESET) return(\"CallBrlyTxtvalPreSet\");\n\tif (ix == CALLBRLYUSGAACCMOD_USGEQ) return(\"CallBrlyUsgAaccMod.usgEq\");\n\tif (ix == CALLBRLYUSGMOD) return(\"CallBrlyUsgMod\");\n\tif (ix == CALLBRLYUSGUPD_REFEQ) return(\"CallBrlyUsgUpd.refEq\");\n\tif (ix == CALLBRLYUSR_PRSEQ) return(\"CallBrlyUsr.prsEq\");\n\tif (ix == CALLBRLYUSR_USGEQ) return(\"CallBrlyUsr.usgEq\");\n\tif (ix == CALLBRLYUSRAACCMOD_USREQ) return(\"CallBrlyUsrAaccMod.usrEq\");\n\tif (ix == CALLBRLYUSRJSTEMOD_USREQ) return(\"CallBrlyUsrJsteMod.usrEq\");\n\tif (ix == CALLBRLYUSRMOD) return(\"CallBrlyUsrMod\");\n\tif (ix == CALLBRLYUSRRUSGMOD_USGEQ) return(\"CallBrlyUsrRusgMod.usgEq\");\n\tif (ix == CALLBRLYUSRRUSGMOD_USREQ) return(\"CallBrlyUsrRusgMod.usrEq\");\n\tif (ix == CALLBRLYUSRUPD_REFEQ) return(\"CallBrlyUsrUpd.refEq\");\n\tif (ix == CALLBRLYVLOCRLOCMOD_DLOEQ) return(\"CallBrlyVlocRlocMod.dloEq\");\n\tif (ix == CALLBRLYVLOCRLOCMOD_OLOEQ) return(\"CallBrlyVlocRlocMod.oloEq\");\n\n\treturn(\"\");\n};\n","avg_line_length":58.003058104,"max_line_length":84,"alphanum_fraction":0.7489323562} {"size":730,"ext":"cpp","lang":"C++","max_stars_count":15.0,"content":"\/\/\n\/\/ Created by sun on 19-7-10.\n\/\/\n#include \n\nusing namespace std;\nusing namespace cv;\n\n\/\/----------------------------------------------------------------------------------------------------------------------\n\/\/ \u6b64\u51fd\u6570\u7528\u4e8e\u5224\u65ad\u76ee\u6807\u662f\u5426\u5207\u6362\n\/\/ ---------------------------------------------------------------------------------------------------------------------\nvoid Energy::changeTarget() {\n if (abs(last_target_polar_angle_judge_change - target_polar_angle) < 20 ||\n abs(last_target_polar_angle_judge_change - target_polar_angle) > 340) {\n change_target = false;\n } else {\n change_target = true;\n last_shoot_time_point = -1000;\n }\n last_target_polar_angle_judge_change = target_polar_angle;\n}","avg_line_length":34.7619047619,"max_line_length":120,"alphanum_fraction":0.4657534247} {"size":30310,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"#include \n\n#include \"UserInterface.h\"\n#include \"IException.h\"\n#include \"IString.h\"\n#include \"Preference.h\"\n#include \"FileName.h\"\n\nusing namespace Isis;\nusing namespace std;\n\nint main(int argc, char *argv[]) {\n Isis::Preference::Preferences(true);\n\n cout << \"Unit test for Isis::UserInterface ...\" << endl;\n\n QString unitTestXml = Isis::FileName(QString(ISISROOT) + \"\/src\/base\/objs\/UserInterface\/unitTest.xml\").expanded();\n QString highpass = Isis::FileName(QString(ISISBUILDDIR) + \"\/bin\/xml\/highpass.xml\").expanded();\n\n char *myArgv[15];\/\/ = {\"unitTest\", \"from=input.cub\", \"to=output.cub\"};\n\n for (int i = 0; i < 15; i++)\n myArgv[i] = new char[128];\n\n try {\n cout << \"Basic FROM\/TO Test\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"unitTest\");\n strcpy(myArgv[myArgc++], \"from=input.cub\");\n strcpy(myArgv[myArgc++], \"to=output.cub\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing param= value Format\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"highpass\");\n strcpy(myArgv[myArgc++], \"from=dog\");\n strcpy(myArgv[myArgc++], \"to=biscuit\");\n strcpy(myArgv[myArgc++], \"line=\");\n strcpy(myArgv[myArgc++], \"3\");\n strcpy(myArgv[myArgc++], \"samp=\");\n strcpy(myArgv[myArgc++], \"3\");\n\n Isis::UserInterface ui(highpass, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing No Arguments (Defaults)\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"unitTest\");\n\n int myArgcQ = myArgc;\n Isis::UserInterface ui(unitTestXml, myArgcQ, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing Basic Array Argument\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"highpass\");\n strcpy(myArgv[myArgc++], \"from=dog\");\n strcpy(myArgv[myArgc++], \"to=(biscuit,bread)\");\n strcpy(myArgv[myArgc++], \"line=\");\n strcpy(myArgv[myArgc++], \"3\");\n strcpy(myArgv[myArgc++], \"samp=\");\n strcpy(myArgv[myArgc++], \"3\");\n\n Isis::UserInterface ui(highpass, myArgc, myArgv);\n vector vals;\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \";\n ui.GetAsString(\"TO\", vals);\n\n for (unsigned int i = 0; i < vals.size(); i++) {\n if (i != 0) cout << \",\";\n\n cout << vals[i];\n }\n cout << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing Common Array Argument\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"highpass\");\n strcpy(myArgv[myArgc++], \"from=dog\");\n strcpy(myArgv[myArgc++], \"to=( \\\"dog\\\" , \\\"cat\\\", \\\" cow \\\", 'frog')\");\n strcpy(myArgv[myArgc++], \"line=\");\n strcpy(myArgv[myArgc++], \"3\");\n strcpy(myArgv[myArgc++], \"samp=\");\n strcpy(myArgv[myArgc++], \"3\");\n\n Isis::UserInterface ui(highpass, myArgc, myArgv);\n vector vals;\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << endl;\n ui.GetAsString(\"TO\", vals);\n\n for(unsigned int i = 0; i < vals.size(); i++) {\n cout << \" >> '\" << vals[i] << \"'\" << endl;\n }\n cout << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing Complicated Array Argument\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"highpass\");\n strcpy(myArgv[myArgc++], \"from=dog\");\n strcpy(myArgv[myArgc++], \"to=(biscuit\\\\\\\\,,'bread,',\\\",b,\\\\\\\\,iscuit2,\\\"\\\\,,)\");\n strcpy(myArgv[myArgc++], \"line=\");\n strcpy(myArgv[myArgc++], \"3\");\n strcpy(myArgv[myArgc++], \"samp=\");\n strcpy(myArgv[myArgc++], \"3\");\n\n Isis::UserInterface ui(highpass, myArgc, myArgv);\n vector vals;\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << endl;\n ui.GetAsString(\"TO\", vals);\n\n for(unsigned int i = 0; i < vals.size(); i++) {\n cout << \" >> \" << vals[i] << endl;\n }\n cout << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing Escaped Array \\\\(\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"to=\\\\(escaped, argument)\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n vector vals;\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << endl;\n ui.GetAsString(\"TO\", vals);\n for(unsigned int i = 0; i < vals.size(); i++) {\n cout << \" >> \" << vals[i] << endl;\n }\n cout << endl;\n }\n\n\n cout << \"Testing Escaped Array \\\\\\\\(\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"to=\\\\\\\\(escaped, argument)\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n vector vals;\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << endl;\n ui.GetAsString(\"TO\", vals);\n for(unsigned int i = 0; i < vals.size(); i++) {\n cout << \" >> \" << vals[i] << endl;\n }\n cout << endl;\n }\n\n\n cout << \"Testing param = value Format\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"highpass\");\n strcpy(myArgv[myArgc++], \"from\");\n strcpy(myArgv[myArgc++], \"=\");\n strcpy(myArgv[myArgc++], \"dog\");\n strcpy(myArgv[myArgc++], \"to\");\n strcpy(myArgv[myArgc++], \"=\");\n strcpy(myArgv[myArgc++], \"bread\");\n strcpy(myArgv[myArgc++], \"line\");\n strcpy(myArgv[myArgc++], \"=\");\n strcpy(myArgv[myArgc++], \"3\");\n strcpy(myArgv[myArgc++], \"samp\");\n strcpy(myArgv[myArgc++], \"=\");\n strcpy(myArgv[myArgc++], \"3\");\n\n Isis::UserInterface ui(highpass, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing Space in Parameter Value\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"unitTest\");\n strcpy(myArgv[myArgc++], \"from=input file.cub\");\n strcpy(myArgv[myArgc++], \"to=output.cub\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing =value\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"unitTest\");\n strcpy(myArgv[myArgc++], \"=input.cub\");\n strcpy(myArgv[myArgc++], \"to\");\n strcpy(myArgv[myArgc++], \"=output.cub\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing param =value\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"highpass\");\n strcpy(myArgv[myArgc++], \"from=dog\");\n strcpy(myArgv[myArgc++], \"to\");\n strcpy(myArgv[myArgc++], \"=bread\");\n strcpy(myArgv[myArgc++], \"line\");\n strcpy(myArgv[myArgc++], \"=\");\n strcpy(myArgv[myArgc++], \"3\");\n strcpy(myArgv[myArgc++], \"samp\");\n strcpy(myArgv[myArgc++], \"=\");\n strcpy(myArgv[myArgc++], \"3\");\n\n Isis::UserInterface ui(highpass, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing mismatched quotes for array-value\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"from=(\\\"hello)\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing array-value ending in backslash\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"from=(hello)\\\\\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing Invalid Parameter\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"$ISISROOT\/bin\/highpass\/highpass\");\n strcpy(myArgv[myArgc++], \"bogus=parameter\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing Invalid Reserved Parameter\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-lastt\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing Reserved Parameter=Invalid Value\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-verbose=(\\\"invalid\\\", \\\"value\\\")\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing Unambiguous Reserved Parameter Resolution (-la)\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-la\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing Ambiguous Reserved Parameter Resolution\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-l\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing unitTest v. .\/unitTest for GUI\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"unitTest\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -PID and -GUI\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-pid=1\");\n strcpy(myArgv[myArgc++], \"-gui\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing ParentId() and TheGui()\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n ui.ParentId();\n ui.TheGui();\n }\n\n\n cout << \"Testing -NOGUI\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-nogui\");\n\n Isis::UserInterface ui(highpass, myArgc, myArgv);\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Starting Batchlist Test\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"unitTest\");\n strcpy(myArgv[myArgc++], \"from=$1\");\n strcpy(myArgv[myArgc++], \"to=$2\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n for(int i = 0; i < ui.BatchListSize(); i++) {\n ui.SetBatchList(i);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n cout << \"Finished Batchlist Test\" << endl;\n cout << endl;\n }\n\n\n \/\/ The following four tests should all catch thrown exceptions -\n \/\/ -BATCHLIST cannot be used with -GUI, -SAVE, -RESTORE, or -LAST\n cout << \"Testing -BATCHLIST with -GUI\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-gui\");\n strcpy(myArgv[myArgc++], \"from=$1\");\n strcpy(myArgv[myArgc++], \"to=$2\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing -BATCHLIST with -SAVE\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-save\");\n strcpy(myArgv[myArgc++], \"from=$1\");\n strcpy(myArgv[myArgc++], \"to=$2\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing -BATCHLIST with -RESTORE\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-restore=unitTest.par\");\n strcpy(myArgv[myArgc++], \"from=$1\");\n strcpy(myArgv[myArgc++], \"to=$2\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing -BATCHLIST with -LAST\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-last\");\n strcpy(myArgv[myArgc++], \"from=$1\");\n strcpy(myArgv[myArgc++], \"to=$2\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing -BATCHLIST with nonexistent .lis file\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-batchlist=doesntExist.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -BATCHLIST with empty .lis file\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTestEmpty.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -BATCHLIST with mismatched columns in .lis file\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTestBadColumns.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -ONERROR=CONTINUE\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n strcpy(myArgv[myArgc++], \"-onerror=continue\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"AbortOnError() returns: \" << ui.AbortOnError() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -ONERROR=ABORT\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n strcpy(myArgv[myArgc++], \"-onerror=abort\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"AbortOnError() returns: \" << ui.AbortOnError() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -ONERROR=badValue\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n strcpy(myArgv[myArgc++], \"-onerror=badValue\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -ONERROR=CONTINUE without -BATCHLIST\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-onerror=continue\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -ERRLIST=value without -BATCHLIST\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-errlist=unitTest.txt\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -ERRLIST with no value\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-errlist\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -ERRLIST=value\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-errlist=unitTestErr.txt\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n for(int i = 0; i < ui.BatchListSize(); i++) {\n ui.SetBatchList(i);\n ui.SetErrorList(i);\n }\n cout << endl;\n }\n\n\n \/\/ evaluating -HELP during a unitTest should throw an exception (instead of exiting)\n cout << \"Testing -HELP Priority (invalid parameters present)\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"from=\");\n strcpy(myArgv[myArgc++], \"test.cub\");\n strcpy(myArgv[myArgc++], \"-invalid\");\n strcpy(myArgv[myArgc++], \"-webhelp\");\n strcpy(myArgv[myArgc++], \"invalid=parameter\");\n strcpy(myArgv[myArgc++], \"-help\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"Evaluating -HELP should have thrown an exception during unit testing\" << endl;\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -HELP=value ...\" << endl;\n cout << endl;\n cout << \"Testing pixelType\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-help=to\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"Evaluating -HELP should have thrown an exception during unit testing\" << endl;\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing inclusive min and max, lessThan, lessThanOrEqual, internalDefault\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-help=testone\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"Evaluating -HELP should have thrown an exception during unit testing\" << endl;\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing odd, noninclusive min and max, greaterThan, greaterThanOrEqual\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-help=testtwo\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"Evaluating -HELP should have thrown an exception during unit testing\" << endl;\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing inclusions, exclusions\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-help=testthree\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"Evaluating -HELP should have thrown an exception during unit testing\" << endl;\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n cout << \"Testing list inclusions, exclusions, defaults\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-help=listtest\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"Evaluating -HELP should have thrown an exception during unit testing\" << endl;\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n cout << \"...End testing -HELP=value\" << endl;\n cout << endl;\n\n\n cout << \"Testing -INFO\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-info\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"GetInfoFlag() returns: \" << ui.GetInfoFlag() << endl;\n cout << \"GetInfoFileName() returns: \" << ui.GetInfoFileName() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -INFO=value\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-info=debug.log\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"GetInfoFlag() returns: \" << ui.GetInfoFlag() << endl;\n cout << \"GetInfoFileName() returns: \" << ui.GetInfoFileName() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -LAST\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-last\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -LAST with other app parameters\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"from=otherParam\");\n strcpy(myArgv[myArgc++], \"-last\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -LOG\" << endl;\n {\n Preference &tempTestPrefs = Isis::Preference::Preferences(true);\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-log\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << tempTestPrefs.findGroup(\"SessionLog\")[\"FileOutput\"] << endl;\n cout << tempTestPrefs.findGroup(\"SessionLog\")[\"FileName\"] << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -LOG=value\" << endl;\n {\n Preference &tempTestPrefs = Isis::Preference::Preferences(true);\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-log=unitTest.prt\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << tempTestPrefs.findGroup(\"SessionLog\")[\"FileOutput\"] << endl;\n cout << tempTestPrefs.findGroup(\"SessionLog\")[\"FileName\"] << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -RESTORE with valid (existing) .par file\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-restore=unitTest.par\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n }\n\n\n cout << \"Testing -RESTORE with corrupt .par file\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-restore=unitTestCorrupt.par\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n cout << \"Testing -RESTORE with invalid (non-existing) .par file\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \"$ISISROOT\/bin\/highpass\");\n strcpy(myArgv[myArgc++], \"-restore=junk.par\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n\n \/\/ testing loadHistory()\n cout << \"Testing -RESTORE with an empty .par file\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-restore=unitTestEmpty.par\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n\n\n \/\/ unitTestLoadHistory.par has more object groups to test loadHistory()\n cout << \"Testing -RESTORE with a more populated .par file\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-restore=unitTestLoadHistory.par\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << endl;\n }\n\n\n \/\/ TestPreferences for unit tests have HistoryRecording set to Off\n cout << \"Testing -SAVE with HistoryRecording Off\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-save=unitTestSaveArgs.par\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n ui.SaveHistory();\n cout << endl;\n }\n\n\n cout << \"Starting -SAVE, -PREFERECE, and -RESTORE Test\" << endl;\n {\n cout << \"Testing -SAVE=value with HistoryRecording On\" << endl;\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"from=saveParam\");\n strcpy(myArgv[myArgc++], \"to=works\");\n strcpy(myArgv[myArgc++], \"-save=unitTestSave.par\");\n strcpy(myArgv[myArgc++], \"-preference=unitTestPrefs\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui.IsInteractive() << endl;\n cout << endl;\n ui.SaveHistory();\n\n cout << \"Restoring Saved Parameters:\" << endl;\n myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-restore=unitTestSave.par\");\n\n Isis::UserInterface ui2(unitTestXml, myArgc, myArgv);\n cout << \"FROM: \" << ui2.GetAsString(\"FROM\") << endl;\n cout << \"TO: \" << ui2.GetAsString(\"TO\") << endl;\n cout << \"GUI: \" << ui2.IsInteractive() << endl;\n cout << endl;\n\n cout << \"Finished -SAVE, PREFERENCE, and -RESTORE Test\" << endl;\n cout << endl;\n }\n\n\n cout << \"Testing SetBatchList()...\" << endl;\n {\n cout << \"Testing with param=array-value\" << endl;\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"from=$$1\");\n strcpy(myArgv[myArgc++], \"to=($2,$2copy)\");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n ui.SetBatchList(0);\n cout << endl;\n\n cout << \"Testing with param= \" << endl;\n myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"from=$1\");\n strcpy(myArgv[myArgc++], \"to= \");\n strcpy(myArgv[myArgc++], \"-batchlist=unitTest.lis\");\n\n Isis::UserInterface ui2(unitTestXml, myArgc, myArgv);\n ui2.SetBatchList(0);\n cout << endl;\n }\n cout << \"...End SetBatchList() Test\" << endl;\n cout << endl;\n\n\n cout << \"Testing SetErrorList() with p_errList == \\\"\\\"\" << endl;\n {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n ui.SetErrorList(0);\n cout << endl;\n }\n\n\n cout << \"Testing -VERBOSE\" << endl;\n {\n Preference &tempTestPrefs = Isis::Preference::Preferences(true);\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"-verbose\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << tempTestPrefs.findGroup(\"SessionLog\")[\"TerminalOutput\"] << endl;\n cout << endl;\n }\n\n\n \/\/ evaluating -webhelp should throw an error during unit test (instead of exiting)\n cout << \"Testing -WEBHELP\" << endl;\n try {\n int myArgc = 0;\n strcpy(myArgv[myArgc++], \".\/unitTest\");\n strcpy(myArgv[myArgc++], \"bogus=parameter\");\n strcpy(myArgv[myArgc++], \"-webhelp\");\n\n Isis::UserInterface ui(unitTestXml, myArgc, myArgv);\n cout << \"Evaluating -WEBHELP should have thrown an exception during unit testing\" << endl;\n }\n catch (Isis::IException &e) {\n e.print();\n cout << endl;\n }\n\n }\n catch (Isis::IException &e) {\n e.print();\n }\n}\n","avg_line_length":28.9770554493,"max_line_length":115,"alphanum_fraction":0.5495546024} {"size":9370,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"\/\/ Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \n#include \"cpu\/tensor_computing_cpu.h\"\n#ifdef _USE_GENERAL\n#include \"cpu\/general\/tensor_computing_general.h\"\n#endif\n#ifdef _USE_X86\n#include \"cpu\/x86\/tensor_computing_x86.h\"\n#endif\n#ifdef _USE_NEON\n#include \"cpu\/arm\/tensor_computing_arm.h\"\n#endif\n#include \"blas_enhance.h\"\n\ntemplate \nstatic EE rnn_transform_filter(TensorDesc filterDesc,\n const T *filterArray,\n RNNParamSpec rnnParamSpec,\n TensorDesc *ftmDesc,\n T *ftmArray)\n{\n if (nullptr == filterArray || nullptr == ftmDesc || nullptr == ftmArray) {\n CHECK_STATUS(NULL_POINTER);\n }\n DataType fdt;\n DataFormat fdf;\n U32 fn, fk, ftm_n, ftm_k;\n CHECK_STATUS(tensor2dGet(filterDesc, &fdt, &fdf, &fn, &fk));\n U32 alignSize = 32;\n EE ret = SUCCESS;\n switch (fdf) {\n case DF_NKN32: {\n ftm_n = fn;\n ftm_k = fk;\n break;\n }\n case DF_NK: {\n \/\/ NK => NKN32\n if (fn % alignSize != 0) {\n return NOT_MATCH;\n }\n ftm_n = fn \/ alignSize;\n ftm_k = fk;\n for (U32 n = 0; n < ftm_n; n++) {\n for (U32 k = 0; k < ftm_k; k++) {\n for (U32 n32 = 0; n32 < alignSize; n32++) {\n ftmArray[n * ftm_k * alignSize + k * alignSize + n32] =\n filterArray[(n * alignSize + n32) * ftm_k + k];\n }\n }\n }\n break;\n }\n default:\n ret = NOT_MATCH;\n break;\n }\n *ftmDesc = tensor2df(fdt, DF_NKN32, fn, fk);\n return ret;\n}\n\nstatic EE rnn_transform_filter_cpu_kernel(TensorDesc filterDesc,\n const void *filterArray,\n RNNParamSpec rnnParamSpec,\n TensorDesc *ftmDesc,\n void *ftmArray)\n{\n EE ret = SUCCESS;\n switch (filterDesc.dt) {\n#ifdef _USE_FP32\n case DT_F32: {\n ret = rnn_transform_filter(\n filterDesc, (const F32 *)filterArray, rnnParamSpec, ftmDesc, (F32 *)ftmArray);\n break;\n }\n#endif\n#ifdef _USE_FP16\n case DT_F16: {\n ret = rnn_transform_filter(\n filterDesc, (const F16 *)filterArray, rnnParamSpec, ftmDesc, (F16 *)ftmArray);\n break;\n }\n#endif\n default:\n ret = NOT_SUPPORTED;\n break;\n }\n return ret;\n}\n\nEE rnn_transform_filter_cpu(const TensorDesc *filterDesc,\n const void **filterArray,\n RNNParamSpec rnnParamSpec,\n TensorDesc *ftmDesc,\n void **ftmArray)\n{\n int num1 = rnnParamSpec.biDirection ? 2 : 1;\n int num2 = rnnParamSpec.numProjection > 0 ? 2 : 1;\n EE ret = SUCCESS;\n for (int i = 0; i < num1 * num2; i++) {\n ret = rnn_transform_filter_cpu_kernel(\n filterDesc[i], filterArray[i], rnnParamSpec, &ftmDesc[i], ftmArray[i]);\n }\n return ret;\n}\n\nEE rnn_transform_filter_bytes_cpu(\n const TensorDesc *filterDesc, RNNParamSpec rnnParamSpec, U32 *bytes)\n{\n if (nullptr == bytes) {\n CHECK_STATUS(NULL_POINTER);\n }\n int num1 = rnnParamSpec.biDirection ? 2 : 1;\n int num2 = rnnParamSpec.numProjection > 0 ? 2 : 1;\n for (int i = 0; i < num1 * num2; i++) {\n bytes[i] = tensorNumBytes(filterDesc[i]);\n }\n return SUCCESS;\n}\n\nEE rnncell_infer_forward_tmp_bytes_cpu(TensorDesc inputDesc,\n TensorDesc filterDesc,\n TensorDesc outputDesc,\n RNNParamSpec rnnParamSpec,\n U32 *bytes,\n Arch arch)\n{\n UNUSED(outputDesc);\n if (nullptr == bytes) {\n CHECK_STATUS(NULL_POINTER);\n }\n DataType idt;\n DataFormat idf;\n U32 batch, xDim;\n CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &batch, &xDim));\n U32 hDim = rnnParamSpec.numOutput;\n U32 column = (rnnParamSpec.numProjection > 0) ? rnnParamSpec.numProjection\n : rnnParamSpec.numOutput;\n *bytes = (hDim + xDim + column * 4) * bytesOf(idt);\n return SUCCESS;\n}\n\nEE rnn_infer_forward_tmp_bytes_cpu(TensorDesc inputDesc,\n TensorDesc filterDesc,\n TensorDesc outputDesc,\n RNNParamSpec rnnParamSpec,\n U32 *bytes,\n Arch arch)\n{\n UNUSED(filterDesc);\n UNUSED(outputDesc);\n if (nullptr == bytes) {\n CHECK_STATUS(NULL_POINTER);\n }\n DataType idt;\n DataFormat idf;\n U32 batch, step, xDim;\n CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &batch, &step, &xDim));\n U32 hDim = rnnParamSpec.numOutput;\n TensorDesc xDesc = tensor2df(idt, DF_NORMAL, batch, xDim);\n CHECK_STATUS(rnncell_infer_forward_tmp_bytes_cpu(\n xDesc, filterDesc, outputDesc, rnnParamSpec, bytes, arch));\n U32 column = (rnnParamSpec.numProjection > 0) ? rnnParamSpec.numProjection\n : rnnParamSpec.numOutput;\n *bytes += batch * (column + hDim) * bytesOf(idt);\n return SUCCESS;\n}\n\nEE rnncell_cpu(TensorDesc xDesc,\n const void *currentX,\n const TensorDesc *filterDesc,\n const void **filter,\n const TensorDesc *biasDesc,\n const void **bias,\n void *state,\n RNNParamSpec rnnParamSpec,\n U32 batchStrideX,\n U32 batchStrideH,\n U32 tmpBytes,\n void *tmp,\n TensorDesc hDesc,\n void *currentH,\n Arch arch)\n{\n EE ret = NOT_SUPPORTED;\n if (IS_GENERAL(arch)) {\n#ifdef _USE_GENERAL\n ret = rnncell_general(xDesc, currentX, filterDesc, filter, biasDesc, bias, state, tmpBytes,\n tmp, rnnParamSpec, batchStrideX, batchStrideH, hDesc, currentH);\n#endif\n#ifdef _USE_X86\n } else if (IS_X86_AVX2(arch)) {\n ret = rnncell_x86(xDesc, currentX, filterDesc, filter, biasDesc, bias, state, tmpBytes, tmp,\n rnnParamSpec, batchStrideX, batchStrideH, hDesc, currentH, arch);\n#endif\n#ifdef _USE_NEON\n } else if (IS_ARM(arch)) {\n ret = rnncell_arm(xDesc, currentX, filterDesc, filter, biasDesc, bias, state, tmpBytes, tmp,\n rnnParamSpec, batchStrideX, batchStrideH, hDesc, currentH, arch);\n#endif\n }\n return ret;\n}\n\nEE rnn_cpu(TensorDesc inputDesc,\n const void *input,\n const TensorDesc *filterDesc,\n const void **filter,\n const TensorDesc *biasDesc,\n const void **bias,\n RNNParamSpec rnnParamSpec,\n U32 tmpBytes,\n void *tmp,\n TensorDesc outputDesc,\n void *output,\n Arch arch)\n{\n UNUSED(outputDesc);\n\n if (nullptr == input || nullptr == filter || nullptr == bias || nullptr == tmp ||\n nullptr == output) {\n CHECK_STATUS(NULL_POINTER);\n }\n\n DataType idt;\n DataFormat idf;\n U32 batch, step, xDim;\n int num1 = rnnParamSpec.biDirection ? 2 : 1;\n CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &batch, &step, &xDim));\n U32 hDim = rnnParamSpec.numOutput;\n U32 column = (rnnParamSpec.numProjection > 0) ? rnnParamSpec.numProjection\n : rnnParamSpec.numOutput;\n\n U8 *cellState = (U8 *)tmp;\n U8 *tmpArray = cellState + batch * (column + hDim) * bytesOf(idt);\n U32 batchStrideX = step * xDim;\n U32 batchStrideH = step * hDim * num1;\n TensorDesc xDesc = tensor2df(idt, DF_NORMAL, batch, xDim);\n TensorDesc hDesc = tensor2df(idt, DF_NORMAL, batch, hDim);\n\n memset(cellState, 0, batch * (column + hDim) * bytesOf(idt));\n for (U32 t = 0; t < step; t++) {\n const U8 *currentX = (const U8 *)input + t * xDim * bytesOf(idt);\n U8 *currentH = (U8 *)output + t * hDim * num1 * bytesOf(idt);\n CHECK_STATUS(rnncell_cpu(xDesc, currentX, filterDesc, filter, biasDesc, bias, cellState,\n rnnParamSpec, batchStrideX, batchStrideH, tmpBytes, tmpArray, hDesc, currentH, arch));\n }\n\n if (rnnParamSpec.biDirection) {\n memset(cellState, 0, batch * (column + hDim) * bytesOf(idt));\n int num2 = (rnnParamSpec.numProjection > 0) ? 2 : 1;\n for (I32 t = step - 1; t >= 0; t--) {\n const U8 *currentX = (const U8 *)input + t * xDim * bytesOf(idt);\n U8 *currentH = (U8 *)output + t * hDim * num1 * bytesOf(idt) + hDim * bytesOf(idt);\n CHECK_STATUS(rnncell_cpu(xDesc, currentX, &filterDesc[num2], &filter[num2],\n &biasDesc[num2], &bias[num2], cellState, rnnParamSpec, batchStrideX, batchStrideH,\n tmpBytes, tmpArray, hDesc, currentH, arch));\n }\n }\n return SUCCESS;\n}\n","avg_line_length":34.197080292,"max_line_length":149,"alphanum_fraction":0.6274279616} {"size":11372,"ext":"cc","lang":"C++","max_stars_count":14668.0,"content":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"device\/gamepad\/raw_input_data_fetcher_win.h\"\n\n#include \n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/cxx17_backports.h\"\n#include \"base\/strings\/sys_string_conversions.h\"\n#include \"base\/trace_event\/trace_event.h\"\n#include \"device\/gamepad\/gamepad_standard_mappings.h\"\n#include \"device\/gamepad\/gamepad_uma.h\"\n#include \"device\/gamepad\/nintendo_controller.h\"\n\nnamespace device {\n\nnamespace {\n\nconst uint16_t DeviceUsages[] = {\n RawInputGamepadDeviceWin::kGenericDesktopJoystick,\n RawInputGamepadDeviceWin::kGenericDesktopGamePad,\n RawInputGamepadDeviceWin::kGenericDesktopMultiAxisController,\n};\n\n} \/\/ namespace\n\nRawInputDataFetcher::RawInputDataFetcher() = default;\n\nRawInputDataFetcher::~RawInputDataFetcher() {\n StopMonitor();\n ClearControllers();\n DCHECK(!window_);\n DCHECK(!events_monitored_);\n}\n\nGamepadSource RawInputDataFetcher::source() {\n return Factory::static_source();\n}\n\nRAWINPUTDEVICE* RawInputDataFetcher::GetRawInputDevices(DWORD flags) {\n size_t usage_count = base::size(DeviceUsages);\n std::unique_ptr devices(new RAWINPUTDEVICE[usage_count]);\n for (size_t i = 0; i < usage_count; ++i) {\n devices[i].dwFlags = flags;\n devices[i].usUsagePage = 1;\n devices[i].usUsage = DeviceUsages[i];\n devices[i].hwndTarget = (flags & RIDEV_REMOVE) ? 0 : window_->hwnd();\n }\n return devices.release();\n}\n\nvoid RawInputDataFetcher::PauseHint(bool pause) {\n if (pause)\n StopMonitor();\n else\n StartMonitor();\n}\n\nvoid RawInputDataFetcher::StartMonitor() {\n if (events_monitored_)\n return;\n\n if (!window_) {\n window_ = std::make_unique();\n if (!window_->Create(base::BindRepeating(\n &RawInputDataFetcher::HandleMessage, base::Unretained(this)))) {\n PLOG(ERROR) << \"Failed to create the raw input window\";\n window_.reset();\n return;\n }\n }\n\n \/\/ Register to receive raw HID input.\n std::unique_ptr devices(\n GetRawInputDevices(RIDEV_INPUTSINK));\n if (!::RegisterRawInputDevices(devices.get(), base::size(DeviceUsages),\n sizeof(RAWINPUTDEVICE))) {\n PLOG(ERROR) << \"RegisterRawInputDevices() failed for RIDEV_INPUTSINK\";\n window_.reset();\n return;\n }\n\n events_monitored_ = true;\n}\n\nvoid RawInputDataFetcher::StopMonitor() {\n if (!events_monitored_)\n return;\n\n \/\/ Stop receiving raw input.\n DCHECK(window_);\n std::unique_ptr devices(GetRawInputDevices(RIDEV_REMOVE));\n\n if (!::RegisterRawInputDevices(devices.get(), base::size(DeviceUsages),\n sizeof(RAWINPUTDEVICE))) {\n PLOG(INFO) << \"RegisterRawInputDevices() failed for RIDEV_REMOVE\";\n }\n\n events_monitored_ = false;\n window_.reset();\n}\n\nbool RawInputDataFetcher::DisconnectUnrecognizedGamepad(int source_id) {\n for (auto it = controllers_.begin(); it != controllers_.end(); ++it) {\n if (it->second->GetSourceId() == source_id) {\n it->second->Shutdown();\n controllers_.erase(it);\n return true;\n }\n }\n return false;\n}\n\nvoid RawInputDataFetcher::ClearControllers() {\n for (const auto& entry : controllers_)\n entry.second->Shutdown();\n controllers_.clear();\n}\n\nvoid RawInputDataFetcher::GetGamepadData(bool devices_changed_hint) {\n if (devices_changed_hint)\n EnumerateDevices();\n\n for (const auto& entry : controllers_) {\n const RawInputGamepadDeviceWin* device = entry.second.get();\n PadState* state = GetPadState(device->GetSourceId());\n if (!state)\n continue;\n\n device->ReadPadState(&state->data);\n }\n}\n\nvoid RawInputDataFetcher::EnumerateDevices() {\n UINT count = 0;\n UINT result =\n ::GetRawInputDeviceList(nullptr, &count, sizeof(RAWINPUTDEVICELIST));\n if (result == static_cast(-1)) {\n PLOG(ERROR) << \"GetRawInputDeviceList() failed\";\n return;\n }\n DCHECK_EQ(0u, result);\n\n std::unique_ptr device_list(\n new RAWINPUTDEVICELIST[count]);\n result = ::GetRawInputDeviceList(device_list.get(), &count,\n sizeof(RAWINPUTDEVICELIST));\n if (result == static_cast(-1)) {\n PLOG(ERROR) << \"GetRawInputDeviceList() failed\";\n return;\n }\n DCHECK_EQ(count, result);\n\n std::unordered_set enumerated_device_handles;\n for (UINT i = 0; i < count; ++i) {\n if (device_list[i].dwType == RIM_TYPEHID) {\n HANDLE device_handle = device_list[i].hDevice;\n auto controller_it = controllers_.find(device_handle);\n\n RawInputGamepadDeviceWin* device;\n if (controller_it != controllers_.end()) {\n device = controller_it->second.get();\n } else {\n int source_id = ++last_source_id_;\n auto new_device = std::make_unique(\n device_handle, source_id);\n if (!new_device->IsValid()) {\n new_device->Shutdown();\n continue;\n }\n\n const int vendor_int = new_device->GetVendorId();\n const int product_int = new_device->GetProductId();\n const int version_number = new_device->GetVersionNumber();\n const std::wstring product_wstring = new_device->GetProductString();\n const std::string product_string = base::SysWideToUTF8(product_wstring);\n const GamepadId gamepad_id = GamepadIdList::Get().GetGamepadId(\n product_string, vendor_int, product_int);\n\n if (NintendoController::IsNintendoController(gamepad_id)) {\n \/\/ Nintendo devices are handled by the Nintendo data fetcher.\n new_device->Shutdown();\n continue;\n }\n\n bool is_recognized = GamepadId::kUnknownGamepad != gamepad_id;\n\n \/\/ Record gamepad metrics before excluding XInput devices. This allows\n \/\/ us to recognize XInput devices even though the XInput API masks\n \/\/ the vendor and product IDs.\n RecordConnectedGamepad(gamepad_id);\n\n \/\/ The presence of \"IG_\" in the device name indicates that this is an\n \/\/ XInput Gamepad. Skip enumerating these devices and let the XInput\n \/\/ path handle it.\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ee417014.aspx\n const std::wstring device_name = new_device->GetDeviceName();\n if (filter_xinput_ && device_name.find(L\"IG_\") != std::wstring::npos) {\n new_device->Shutdown();\n continue;\n }\n\n PadState* state = GetPadState(source_id, is_recognized);\n if (!state) {\n new_device->Shutdown();\n continue; \/\/ No slot available for this gamepad.\n }\n\n auto emplace_result =\n controllers_.emplace(device_handle, std::move(new_device));\n device = emplace_result.first->second.get();\n\n Gamepad& pad = state->data;\n pad.connected = true;\n\n pad.vibration_actuator.type = GamepadHapticActuatorType::kDualRumble;\n pad.vibration_actuator.not_null = device->SupportsVibration();\n\n state->mapper = GetGamepadStandardMappingFunction(\n product_string, vendor_int, product_int,\n \/*hid_specification_version=*\/0, version_number,\n GAMEPAD_BUS_UNKNOWN);\n state->axis_mask = 0;\n state->button_mask = 0;\n\n UpdateGamepadStrings(product_string, vendor_int, product_int,\n state->mapper != nullptr, pad);\n }\n\n enumerated_device_handles.insert(device_handle);\n }\n }\n\n \/\/ Clear out old controllers that weren't part of this enumeration pass.\n auto controller_it = controllers_.begin();\n while (controller_it != controllers_.end()) {\n if (enumerated_device_handles.find(controller_it->first) ==\n enumerated_device_handles.end()) {\n controller_it->second->Shutdown();\n controller_it = controllers_.erase(controller_it);\n } else {\n ++controller_it;\n }\n }\n}\n\nRawInputGamepadDeviceWin* RawInputDataFetcher::DeviceFromSourceId(\n int source_id) {\n for (const auto& entry : controllers_) {\n if (entry.second->GetSourceId() == source_id)\n return entry.second.get();\n }\n return nullptr;\n}\n\nvoid RawInputDataFetcher::PlayEffect(\n int source_id,\n mojom::GamepadHapticEffectType type,\n mojom::GamepadEffectParametersPtr params,\n mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback callback,\n scoped_refptr callback_runner) {\n RawInputGamepadDeviceWin* device = DeviceFromSourceId(source_id);\n if (!device) {\n RunVibrationCallback(\n std::move(callback), std::move(callback_runner),\n mojom::GamepadHapticsResult::GamepadHapticsResultError);\n return;\n }\n\n if (!device->SupportsVibration()) {\n RunVibrationCallback(\n std::move(callback), std::move(callback_runner),\n mojom::GamepadHapticsResult::GamepadHapticsResultNotSupported);\n return;\n }\n\n device->PlayEffect(type, std::move(params), std::move(callback),\n std::move(callback_runner));\n}\n\nvoid RawInputDataFetcher::ResetVibration(\n int source_id,\n mojom::GamepadHapticsManager::ResetVibrationActuatorCallback callback,\n scoped_refptr callback_runner) {\n RawInputGamepadDeviceWin* device = DeviceFromSourceId(source_id);\n if (!device) {\n RunVibrationCallback(\n std::move(callback), std::move(callback_runner),\n mojom::GamepadHapticsResult::GamepadHapticsResultError);\n return;\n }\n\n if (!device->SupportsVibration()) {\n RunVibrationCallback(\n std::move(callback), std::move(callback_runner),\n mojom::GamepadHapticsResult::GamepadHapticsResultNotSupported);\n return;\n }\n\n device->ResetVibration(std::move(callback), std::move(callback_runner));\n}\n\nLRESULT RawInputDataFetcher::OnInput(HRAWINPUT input_handle) {\n \/\/ Get the size of the input record.\n UINT size = 0;\n UINT result = ::GetRawInputData(input_handle, RID_INPUT, nullptr, &size,\n sizeof(RAWINPUTHEADER));\n if (result == static_cast(-1)) {\n PLOG(ERROR) << \"GetRawInputData() failed\";\n return 0;\n }\n DCHECK_EQ(0u, result);\n\n \/\/ Retrieve the input record.\n std::unique_ptr buffer(new uint8_t[size]);\n RAWINPUT* input = reinterpret_cast(buffer.get());\n result = ::GetRawInputData(input_handle, RID_INPUT, buffer.get(), &size,\n sizeof(RAWINPUTHEADER));\n if (result == static_cast(-1)) {\n PLOG(ERROR) << \"GetRawInputData() failed\";\n return 0;\n }\n DCHECK_EQ(size, result);\n\n \/\/ Notify the observer about events generated locally.\n if (input->header.dwType == RIM_TYPEHID && input->header.hDevice != NULL) {\n auto it = controllers_.find(input->header.hDevice);\n if (it != controllers_.end())\n it->second->UpdateGamepad(input);\n }\n\n return ::DefRawInputProc(&input, 1, sizeof(RAWINPUTHEADER));\n}\n\nbool RawInputDataFetcher::HandleMessage(UINT message,\n WPARAM wparam,\n LPARAM lparam,\n LRESULT* result) {\n switch (message) {\n case WM_INPUT:\n *result = OnInput(reinterpret_cast(lparam));\n return true;\n\n default:\n return false;\n }\n}\n\n} \/\/ namespace device\n","avg_line_length":32.1242937853,"max_line_length":80,"alphanum_fraction":0.6728807598} {"size":9357,"ext":"cc","lang":"C++","max_stars_count":2.0,"content":"\/*\n *\n * Copyright 2017 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/core\/end2end\/end2end_tests.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"src\/core\/lib\/channel\/channel_args.h\"\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"src\/core\/lib\/gpr\/useful.h\"\n#include \"src\/core\/lib\/iomgr\/exec_ctx.h\"\n#include \"src\/core\/lib\/transport\/static_metadata.h\"\n\n#include \"test\/core\/end2end\/cq_verifier.h\"\n#include \"test\/core\/end2end\/tests\/cancel_test_helpers.h\"\n\nstatic void* tag(intptr_t t) { return reinterpret_cast(t); }\n\nstatic grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,\n const char* test_name,\n grpc_channel_args* client_args,\n grpc_channel_args* server_args) {\n grpc_end2end_test_fixture f;\n gpr_log(GPR_INFO, \"Running test: %s\/%s\", test_name, config.name);\n f = config.create_fixture(client_args, server_args);\n config.init_server(&f, server_args);\n config.init_client(&f, client_args);\n return f;\n}\n\nstatic gpr_timespec n_seconds_from_now(int n) {\n return grpc_timeout_seconds_to_deadline(n);\n}\n\nstatic gpr_timespec five_seconds_from_now(void) {\n return n_seconds_from_now(5);\n}\n\nstatic void drain_cq(grpc_completion_queue* cq) {\n grpc_event ev;\n do {\n ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr);\n } while (ev.type != GRPC_QUEUE_SHUTDOWN);\n}\n\nstatic void shutdown_server(grpc_end2end_test_fixture* f) {\n if (!f->server) return;\n grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000));\n GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000),\n grpc_timeout_seconds_to_deadline(5),\n nullptr)\n .type == GRPC_OP_COMPLETE);\n grpc_server_destroy(f->server);\n f->server = nullptr;\n}\n\nstatic void shutdown_client(grpc_end2end_test_fixture* f) {\n if (!f->client) return;\n grpc_channel_destroy(f->client);\n f->client = nullptr;\n}\n\nstatic void end_test(grpc_end2end_test_fixture* f) {\n shutdown_server(f);\n shutdown_client(f);\n\n grpc_completion_queue_shutdown(f->cq);\n drain_cq(f->cq);\n grpc_completion_queue_destroy(f->cq);\n grpc_completion_queue_destroy(f->shutdown_cq);\n}\n\n\/\/ Tests that we don't make any further attempts after we exceed the\n\/\/ max buffer size.\n\/\/ - 1 retry allowed for ABORTED status\n\/\/ - buffer size set to 2 bytes\n\/\/ - client sends a 3-byte message\n\/\/ - first attempt gets ABORTED but is not retried\nstatic void test_retry_exceeds_buffer_size_in_initial_batch(\n grpc_end2end_test_config config) {\n grpc_call* c;\n grpc_call* s;\n grpc_op ops[6];\n grpc_op* op;\n grpc_metadata_array initial_metadata_recv;\n grpc_metadata_array trailing_metadata_recv;\n grpc_metadata_array request_metadata_recv;\n grpc_call_details call_details;\n grpc_slice request_payload_slice = grpc_slice_from_static_string(\"foo\");\n grpc_slice response_payload_slice = grpc_slice_from_static_string(\"bar\");\n grpc_byte_buffer* request_payload =\n grpc_raw_byte_buffer_create(&request_payload_slice, 1);\n grpc_byte_buffer* response_payload =\n grpc_raw_byte_buffer_create(&response_payload_slice, 1);\n grpc_byte_buffer* request_payload_recv = nullptr;\n grpc_byte_buffer* response_payload_recv = nullptr;\n grpc_status_code status;\n grpc_call_error error;\n grpc_slice details;\n int was_cancelled = 2;\n char* peer;\n\n grpc_arg args[] = {\n grpc_channel_arg_integer_create(\n const_cast(GRPC_ARG_ENABLE_RETRIES), 1),\n grpc_channel_arg_string_create(\n const_cast(GRPC_ARG_SERVICE_CONFIG),\n const_cast(\n \"{\\n\"\n \" \\\"methodConfig\\\": [ {\\n\"\n \" \\\"name\\\": [\\n\"\n \" { \\\"service\\\": \\\"service\\\", \\\"method\\\": \\\"method\\\" }\\n\"\n \" ],\\n\"\n \" \\\"retryPolicy\\\": {\\n\"\n \" \\\"maxAttempts\\\": 2,\\n\"\n \" \\\"initialBackoff\\\": \\\"1s\\\",\\n\"\n \" \\\"maxBackoff\\\": \\\"120s\\\",\\n\"\n \" \\\"backoffMultiplier\\\": 1.6,\\n\"\n \" \\\"retryableStatusCodes\\\": [ \\\"ABORTED\\\" ]\\n\"\n \" }\\n\"\n \" } ]\\n\"\n \"}\")),\n grpc_channel_arg_integer_create(\n const_cast(GRPC_ARG_PER_RPC_RETRY_BUFFER_SIZE), 2),\n };\n grpc_channel_args client_args = {GPR_ARRAY_SIZE(args), args};\n grpc_end2end_test_fixture f =\n begin_test(config, \"retry_exceeds_buffer_size_in_initial_batch\",\n &client_args, nullptr);\n\n cq_verifier* cqv = cq_verifier_create(f.cq);\n\n gpr_timespec deadline = five_seconds_from_now();\n c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,\n grpc_slice_from_static_string(\"\/service\/method\"),\n nullptr, deadline, nullptr);\n GPR_ASSERT(c);\n\n peer = grpc_call_get_peer(c);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"client_peer_before_call=%s\", peer);\n gpr_free(peer);\n\n grpc_metadata_array_init(&initial_metadata_recv);\n grpc_metadata_array_init(&trailing_metadata_recv);\n grpc_metadata_array_init(&request_metadata_recv);\n grpc_call_details_init(&call_details);\n grpc_slice status_details = grpc_slice_from_static_string(\"xyz\");\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op++;\n op->op = GRPC_OP_SEND_MESSAGE;\n op->data.send_message.send_message = request_payload;\n op++;\n op->op = GRPC_OP_RECV_MESSAGE;\n op->data.recv_message.recv_message = &response_payload_recv;\n op++;\n op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;\n op++;\n op->op = GRPC_OP_RECV_INITIAL_METADATA;\n op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;\n op++;\n op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;\n op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;\n op->data.recv_status_on_client.status = &status;\n op->data.recv_status_on_client.status_details = &details;\n op++;\n error = grpc_call_start_batch(c, ops, static_cast(op - ops), tag(1),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n error =\n grpc_server_request_call(f.server, &s, &call_details,\n &request_metadata_recv, f.cq, f.cq, tag(101));\n GPR_ASSERT(GRPC_CALL_OK == error);\n CQ_EXPECT_COMPLETION(cqv, tag(101), true);\n cq_verify(cqv);\n\n peer = grpc_call_get_peer(s);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"server_peer=%s\", peer);\n gpr_free(peer);\n peer = grpc_call_get_peer(c);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"client_peer=%s\", peer);\n gpr_free(peer);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op++;\n op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;\n op->data.send_status_from_server.trailing_metadata_count = 0;\n op->data.send_status_from_server.status = GRPC_STATUS_ABORTED;\n op->data.send_status_from_server.status_details = &status_details;\n op++;\n op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;\n op->data.recv_close_on_server.cancelled = &was_cancelled;\n op++;\n error = grpc_call_start_batch(s, ops, static_cast(op - ops), tag(102),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n CQ_EXPECT_COMPLETION(cqv, tag(102), true);\n CQ_EXPECT_COMPLETION(cqv, tag(1), true);\n cq_verify(cqv);\n\n GPR_ASSERT(status == GRPC_STATUS_ABORTED);\n GPR_ASSERT(0 == grpc_slice_str_cmp(details, \"xyz\"));\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, \"\/service\/method\"));\n GPR_ASSERT(0 == call_details.flags);\n GPR_ASSERT(was_cancelled == 0);\n\n grpc_slice_unref(details);\n grpc_metadata_array_destroy(&initial_metadata_recv);\n grpc_metadata_array_destroy(&trailing_metadata_recv);\n grpc_metadata_array_destroy(&request_metadata_recv);\n grpc_call_details_destroy(&call_details);\n grpc_byte_buffer_destroy(request_payload);\n grpc_byte_buffer_destroy(response_payload);\n grpc_byte_buffer_destroy(request_payload_recv);\n grpc_byte_buffer_destroy(response_payload_recv);\n\n grpc_call_unref(c);\n grpc_call_unref(s);\n\n cq_verifier_destroy(cqv);\n\n end_test(&f);\n config.tear_down_data(&f);\n}\n\nvoid retry_exceeds_buffer_size_in_initial_batch(\n grpc_end2end_test_config config) {\n GPR_ASSERT(config.feature_mask & FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL);\n test_retry_exceeds_buffer_size_in_initial_batch(config);\n}\n\nvoid retry_exceeds_buffer_size_in_initial_batch_pre_init(void) {}\n","avg_line_length":35.0449438202,"max_line_length":80,"alphanum_fraction":0.7011862777} {"size":1021,"ext":"hpp","lang":"C++","max_stars_count":null,"content":"\/\/\n\/\/ MessagePack for C++ static resolution routine\n\/\/\n\/\/ Copyright (C) 2016 KONDO Takatoshi\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n#ifndef MSGPACK_V2_OBJECT_DECL_HPP\n#define MSGPACK_V2_OBJECT_DECL_HPP\n\n#include \"rpc\/msgpack\/v1\/object_decl.hpp\"\n#include \"rpc\/msgpack\/adaptor\/adaptor_base.hpp\"\n\nnamespace clmdep_msgpack {\n\n\/\/\/ @cond\nMSGPACK_API_VERSION_NAMESPACE(v2) {\n\/\/\/ @endcond\n\nusing v1::object_handle;\n\nnamespace detail {\n\nusing v1::detail::add_ext_type_size;\n\n} \/\/ namespace detail\n\nusing v1::aligned_zone_size;\n\nusing v1::clone;\n\nnamespace detail {\n\nusing v1::detail::packer_serializer;\n\n} \/\/ namespace detail\n\nusing v1::object_parser;\nusing v1::object_pack_visitor;\nusing v1::object_stringize_visitor;\n\nusing v1::operator==;\nusing v1::operator!=;\n\n\/\/\/ @cond\n} \/\/ MSGPACK_API_VERSION_NAMESPACE(v2)\n\/\/\/ @endcond\n\n} \/\/ namespace clmdep_msgpack\n\n#endif \/\/ MSGPACK_V2_OBJECT_DECL_HPP\n","avg_line_length":18.9074074074,"max_line_length":64,"alphanum_fraction":0.7482859941} {"size":17407,"ext":"cpp","lang":"C++","max_stars_count":3.0,"content":"\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n\/*\n * Dialog services for PIP.\n *\/\n#include \"nsCOMPtr.h\"\n#include \"nsString.h\"\n#include \"nsXPIDLString.h\"\n#include \"nsReadableUtils.h\"\n#include \"nsIDOMWindow.h\"\n#include \"nsIDialogParamBlock.h\"\n#include \"nsIComponentManager.h\"\n#include \"nsIServiceManager.h\"\n#include \"nsIStringBundle.h\"\n#include \"nsIInterfaceRequestor.h\"\n#include \"nsIInterfaceRequestorUtils.h\"\n#include \"nsIX509Cert.h\"\n#include \"nsIX509CertDB.h\"\n#include \"nsIDateTimeFormat.h\"\n#include \"nsDateTimeFormatCID.h\"\n#include \"nsPromiseFlatString.h\"\n\n#include \"nsNSSDialogs.h\"\n#include \"nsPKIParamBlock.h\"\n#include \"nsIKeygenThread.h\"\n#include \"nsIProtectedAuthThread.h\"\n#include \"nsNSSDialogHelper.h\"\n#include \"nsIWindowWatcher.h\"\n#include \"nsIX509CertValidity.h\"\n#include \"nsICRLInfo.h\"\n\n#define PIPSTRING_BUNDLE_URL \"chrome:\/\/pippki\/locale\/pippki.properties\"\n\n\/* ==== *\/\n\nnsNSSDialogs::nsNSSDialogs()\n{\n}\n\nnsNSSDialogs::~nsNSSDialogs()\n{\n}\n\nNS_IMPL_THREADSAFE_ISUPPORTS8(nsNSSDialogs, nsITokenPasswordDialogs,\n nsICertificateDialogs,\n nsIClientAuthDialogs,\n nsICertPickDialogs,\n nsITokenDialogs,\n nsIDOMCryptoDialogs,\n nsIGeneratingKeypairInfoDialogs,\n nsISSLCertErrorDialog)\n\nnsresult\nnsNSSDialogs::Init()\n{\n nsresult rv;\n\n nsCOMPtr service =\n do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);\n if (NS_FAILED(rv)) return rv;\n \n rv = service->CreateBundle(PIPSTRING_BUNDLE_URL,\n getter_AddRefs(mPIPStringBundle));\n return rv;\n}\n\nnsresult\nnsNSSDialogs::SetPassword(nsIInterfaceRequestor *ctx,\n const PRUnichar *tokenName, bool* _canceled)\n{\n nsresult rv;\n\n *_canceled = false;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n\n nsCOMPtr block =\n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n\n \/\/ void ChangePassword(in wstring tokenName, out int status);\n rv = block->SetString(1, tokenName);\n if (NS_FAILED(rv)) return rv;\n\n rv = nsNSSDialogHelper::openDialog(parent,\n \"chrome:\/\/pippki\/content\/changepassword.xul\",\n block);\n\n if (NS_FAILED(rv)) return rv;\n\n int32_t status;\n\n rv = block->GetInt(1, &status);\n if (NS_FAILED(rv)) return rv;\n\n *_canceled = (status == 0)?true:false;\n\n return rv;\n}\n\nnsresult\nnsNSSDialogs::GetPassword(nsIInterfaceRequestor *ctx,\n const PRUnichar *tokenName, \n PRUnichar **_password,\n bool* _canceled)\n{\n nsresult rv;\n *_canceled = false;\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n nsCOMPtr block = \n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n \/\/ Set the token name in the window\n rv = block->SetString(1, tokenName);\n if (NS_FAILED(rv)) return rv;\n \/\/ open up the window\n rv = nsNSSDialogHelper::openDialog(parent,\n \"chrome:\/\/pippki\/content\/getpassword.xul\",\n block);\n if (NS_FAILED(rv)) return rv;\n \/\/ see if user canceled\n int32_t status;\n rv = block->GetInt(1, &status);\n if (NS_FAILED(rv)) return rv;\n *_canceled = (status == 0) ? true : false;\n if (!*_canceled) {\n \/\/ retrieve the password\n rv = block->GetString(2, _password);\n }\n return rv;\n}\n\nNS_IMETHODIMP \nnsNSSDialogs::CrlImportStatusDialog(nsIInterfaceRequestor *ctx, nsICRLInfo *crl)\n{\n nsresult rv;\n\n nsCOMPtr block =\n do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID,&rv);\n if (NS_FAILED(rv))\n return rv;\n \n rv = block->SetISupportAtIndex(1, crl);\n if (NS_FAILED(rv))\n return rv;\n\n rv = nsNSSDialogHelper::openDialog(nullptr,\n \"chrome:\/\/pippki\/content\/crlImportDialog.xul\",\n block,\n false);\n return NS_OK;\n}\n\nNS_IMETHODIMP \nnsNSSDialogs::ConfirmDownloadCACert(nsIInterfaceRequestor *ctx, \n nsIX509Cert *cert,\n uint32_t *_trust,\n bool *_retval)\n{\n nsresult rv;\n\n *_retval = true;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n\n nsCOMPtr block =\n do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID);\n if (!block)\n return NS_ERROR_FAILURE;\n\n rv = block->SetISupportAtIndex(1, cert);\n if (NS_FAILED(rv))\n return rv;\n\n rv = nsNSSDialogHelper::openDialog(parent, \n \"chrome:\/\/pippki\/content\/downloadcert.xul\",\n block);\n if (NS_FAILED(rv)) return rv;\n\n int32_t status;\n int32_t ssl, email, objsign;\n\n nsCOMPtr dlgParamBlock = do_QueryInterface(block);\n \n rv = dlgParamBlock->GetInt(1, &status);\n if (NS_FAILED(rv)) return rv;\n rv = dlgParamBlock->GetInt(2, &ssl);\n if (NS_FAILED(rv)) return rv;\n rv = dlgParamBlock->GetInt(3, &email);\n if (NS_FAILED(rv)) return rv;\n rv = dlgParamBlock->GetInt(4, &objsign);\n if (NS_FAILED(rv)) return rv;\n \n *_trust = nsIX509CertDB::UNTRUSTED;\n *_trust |= (ssl) ? nsIX509CertDB::TRUSTED_SSL : 0;\n *_trust |= (email) ? nsIX509CertDB::TRUSTED_EMAIL : 0;\n *_trust |= (objsign) ? nsIX509CertDB::TRUSTED_OBJSIGN : 0;\n\n *_retval = (status == 0)?false:true;\n\n return rv;\n}\n\n\nNS_IMETHODIMP \nnsNSSDialogs::NotifyCACertExists(nsIInterfaceRequestor *ctx)\n{\n nsresult rv;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n\n nsCOMPtr block =\n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n\n \n rv = nsNSSDialogHelper::openDialog(parent, \n \"chrome:\/\/pippki\/content\/cacertexists.xul\",\n block);\n\n return rv;\n}\n\n\nNS_IMETHODIMP\nnsNSSDialogs::ChooseCertificate(nsIInterfaceRequestor *ctx, const PRUnichar *cn, const PRUnichar *organization, const PRUnichar *issuer, const PRUnichar **certNickList, const PRUnichar **certDetailsList, uint32_t count, int32_t *selectedIndex, bool *canceled) \n{\n nsresult rv;\n uint32_t i;\n\n *canceled = false;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n\n nsCOMPtr block =\n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n\n block->SetNumberStrings(4+count*2);\n\n rv = block->SetString(0, cn);\n if (NS_FAILED(rv)) return rv;\n\n rv = block->SetString(1, organization);\n if (NS_FAILED(rv)) return rv;\n\n rv = block->SetString(2, issuer);\n if (NS_FAILED(rv)) return rv;\n\n for (i = 0; i < count; i++) {\n rv = block->SetString(i+3, certNickList[i]);\n if (NS_FAILED(rv)) return rv;\n }\n\n for (i = 0; i < count; i++) {\n rv = block->SetString(i+count+3, certDetailsList[i]);\n if (NS_FAILED(rv)) return rv;\n }\n\n rv = block->SetInt(0, count);\n if (NS_FAILED(rv)) return rv;\n\n rv = nsNSSDialogHelper::openDialog(nullptr,\n \"chrome:\/\/pippki\/content\/clientauthask.xul\",\n block);\n if (NS_FAILED(rv)) return rv;\n\n int32_t status;\n rv = block->GetInt(0, &status);\n if (NS_FAILED(rv)) return rv;\n\n nsCOMPtr extraResult = do_QueryInterface(ctx);\n if (extraResult) {\n int32_t rememberSelection;\n rv = block->GetInt(2, &rememberSelection);\n if (NS_SUCCEEDED(rv)) {\n extraResult->SetRememberClientAuthCertificate(rememberSelection!=0);\n }\n }\n\n *canceled = (status == 0)?true:false;\n if (!*canceled) {\n \/\/ retrieve the nickname\n rv = block->GetInt(1, selectedIndex);\n }\n return rv;\n}\n\n\nNS_IMETHODIMP\nnsNSSDialogs::PickCertificate(nsIInterfaceRequestor *ctx, \n const PRUnichar **certNickList, \n const PRUnichar **certDetailsList, \n uint32_t count, \n int32_t *selectedIndex, \n bool *canceled) \n{\n nsresult rv;\n uint32_t i;\n\n *canceled = false;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n\n nsCOMPtr block =\n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n\n block->SetNumberStrings(1+count*2);\n\n for (i = 0; i < count; i++) {\n rv = block->SetString(i, certNickList[i]);\n if (NS_FAILED(rv)) return rv;\n }\n\n for (i = 0; i < count; i++) {\n rv = block->SetString(i+count, certDetailsList[i]);\n if (NS_FAILED(rv)) return rv;\n }\n\n rv = block->SetInt(0, count);\n if (NS_FAILED(rv)) return rv;\n\n rv = block->SetInt(1, *selectedIndex);\n if (NS_FAILED(rv)) return rv;\n\n rv = nsNSSDialogHelper::openDialog(nullptr,\n \"chrome:\/\/pippki\/content\/certpicker.xul\",\n block);\n if (NS_FAILED(rv)) return rv;\n\n int32_t status;\n\n rv = block->GetInt(0, &status);\n if (NS_FAILED(rv)) return rv;\n\n *canceled = (status == 0)?true:false;\n if (!*canceled) {\n rv = block->GetInt(1, selectedIndex);\n }\n return rv;\n}\n\n\nNS_IMETHODIMP \nnsNSSDialogs::SetPKCS12FilePassword(nsIInterfaceRequestor *ctx, \n nsAString &_password,\n bool *_retval)\n{\n nsresult rv;\n *_retval = true;\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n nsCOMPtr block =\n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n \/\/ open up the window\n rv = nsNSSDialogHelper::openDialog(parent,\n \"chrome:\/\/pippki\/content\/setp12password.xul\",\n block);\n if (NS_FAILED(rv)) return rv;\n \/\/ see if user canceled\n int32_t status;\n rv = block->GetInt(1, &status);\n if (NS_FAILED(rv)) return rv;\n *_retval = (status == 0) ? false : true;\n if (*_retval) {\n \/\/ retrieve the password\n PRUnichar *pw;\n rv = block->GetString(2, &pw);\n if (NS_SUCCEEDED(rv)) {\n _password = pw;\n nsMemory::Free(pw);\n }\n }\n return rv;\n}\n\nNS_IMETHODIMP \nnsNSSDialogs::GetPKCS12FilePassword(nsIInterfaceRequestor *ctx, \n nsAString &_password,\n bool *_retval)\n{\n nsresult rv;\n *_retval = true;\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n nsCOMPtr block =\n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n \/\/ open up the window\n rv = nsNSSDialogHelper::openDialog(parent,\n \"chrome:\/\/pippki\/content\/getp12password.xul\",\n block);\n if (NS_FAILED(rv)) return rv;\n \/\/ see if user canceled\n int32_t status;\n rv = block->GetInt(1, &status);\n if (NS_FAILED(rv)) return rv;\n *_retval = (status == 0) ? false : true;\n if (*_retval) {\n \/\/ retrieve the password\n PRUnichar *pw;\n rv = block->GetString(2, &pw);\n if (NS_SUCCEEDED(rv)) {\n _password = pw;\n nsMemory::Free(pw);\n }\n }\n return rv;\n}\n\n\/* void viewCert (in nsIX509Cert cert); *\/\nNS_IMETHODIMP \nnsNSSDialogs::ViewCert(nsIInterfaceRequestor *ctx, \n nsIX509Cert *cert)\n{\n nsresult rv;\n\n nsCOMPtr block =\n do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID);\n if (!block)\n return NS_ERROR_FAILURE;\n\n rv = block->SetISupportAtIndex(1, cert);\n if (NS_FAILED(rv))\n return rv;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(ctx);\n\n rv = nsNSSDialogHelper::openDialog(parent,\n \"chrome:\/\/pippki\/content\/certViewer.xul\",\n block,\n false);\n return rv;\n}\n\nNS_IMETHODIMP\nnsNSSDialogs::DisplayGeneratingKeypairInfo(nsIInterfaceRequestor *aCtx, nsIKeygenThread *runnable) \n{\n nsresult rv;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(aCtx);\n\n rv = nsNSSDialogHelper::openDialog(parent,\n \"chrome:\/\/pippki\/content\/createCertInfo.xul\",\n runnable);\n return rv;\n}\n\nNS_IMETHODIMP\nnsNSSDialogs::ChooseToken(nsIInterfaceRequestor *aCtx, const PRUnichar **aTokenList, uint32_t aCount, PRUnichar **aTokenChosen, bool *aCanceled) {\n nsresult rv;\n uint32_t i;\n\n *aCanceled = false;\n\n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(aCtx);\n\n nsCOMPtr block =\n do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);\n if (!block) return NS_ERROR_FAILURE;\n\n block->SetNumberStrings(aCount);\n\n for (i = 0; i < aCount; i++) {\n rv = block->SetString(i, aTokenList[i]);\n if (NS_FAILED(rv)) return rv;\n }\n\n rv = block->SetInt(0, aCount);\n if (NS_FAILED(rv)) return rv;\n\n rv = nsNSSDialogHelper::openDialog(nullptr,\n \"chrome:\/\/pippki\/content\/choosetoken.xul\",\n block);\n if (NS_FAILED(rv)) return rv;\n\n int32_t status;\n\n rv = block->GetInt(0, &status);\n if (NS_FAILED(rv)) return rv;\n\n *aCanceled = (status == 0)?true:false;\n if (!*aCanceled) {\n \/\/ retrieve the nickname\n rv = block->GetString(0, aTokenChosen);\n }\n return rv;\n}\n\n\/* boolean ConfirmKeyEscrow (in nsIX509Cert escrowAuthority); *\/\nNS_IMETHODIMP \nnsNSSDialogs::ConfirmKeyEscrow(nsIX509Cert *escrowAuthority, bool *_retval)\n \n{\n *_retval = false;\n\n nsresult rv;\n\n nsCOMPtr block =\n do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID);\n if (!block)\n return NS_ERROR_FAILURE;\n\n rv = block->SetISupportAtIndex(1, escrowAuthority);\n if (NS_FAILED(rv))\n return rv;\n\n rv = nsNSSDialogHelper::openDialog(nullptr,\n \"chrome:\/\/pippki\/content\/escrowWarn.xul\",\n block);\n\n if (NS_FAILED(rv))\n return rv;\n\n int32_t status=0;\n nsCOMPtr dlgParamBlock = do_QueryInterface(block);\n rv = dlgParamBlock->GetInt(1, &status);\n \n if (status) {\n *_retval = true;\n } \n return rv;\n}\n\nNS_IMETHODIMP\nnsNSSDialogs::DisplayProtectedAuth(nsIInterfaceRequestor *aCtx, nsIProtectedAuthThread *runnable)\n{\n \/\/ We cannot use nsNSSDialogHelper here. We cannot allow close widget\n \/\/ in the window because protected authentication is interruptible\n \/\/ from user interface and changing nsNSSDialogHelper's static variable\n \/\/ would not be thread-safe\n \n nsresult rv = NS_ERROR_FAILURE;\n \n \/\/ Get the parent window for the dialog\n nsCOMPtr parent = do_GetInterface(aCtx);\n \n nsCOMPtr windowWatcher = \n do_GetService(\"@mozilla.org\/embedcomp\/window-watcher;1\", &rv);\n if (NS_FAILED(rv))\n return rv;\n \n if (!parent) {\n windowWatcher->GetActiveWindow(getter_AddRefs(parent));\n }\n \n nsCOMPtr newWindow;\n rv = windowWatcher->OpenWindow(parent,\n \"chrome:\/\/pippki\/content\/protectedAuth.xul\",\n \"_blank\",\n \"centerscreen,chrome,modal,titlebar,close=no\",\n runnable,\n getter_AddRefs(newWindow));\n \n return rv;\n}\n\nNS_IMETHODIMP\nnsNSSDialogs::ShowCertError(nsIInterfaceRequestor *ctx, \n nsISSLStatus *status, \n nsIX509Cert *cert, \n const nsAString & textErrorMessage, \n const nsAString & htmlErrorMessage, \n const nsACString & hostName, \n uint32_t portNumber)\n{\n nsCOMPtr block =\n do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID);\n if (!block)\n return NS_ERROR_OUT_OF_MEMORY;\n\n nsCOMPtr dialogBlock = do_QueryInterface(block);\n\n nsresult rv;\n rv = dialogBlock->SetInt(1, portNumber);\n if (NS_FAILED(rv))\n return rv; \n\n rv = dialogBlock->SetString(1, NS_ConvertUTF8toUTF16(hostName).get());\n if (NS_FAILED(rv))\n return rv;\n \n rv = dialogBlock->SetString(2, PromiseFlatString(textErrorMessage).get());\n if (NS_FAILED(rv))\n return rv;\n \n rv = block->SetISupportAtIndex(1, cert);\n if (NS_FAILED(rv))\n return rv;\n\n rv = nsNSSDialogHelper::openDialog(nullptr, \n \"chrome:\/\/pippki\/content\/certerror.xul\",\n block);\n return rv;\n}\n","avg_line_length":28.4893617021,"max_line_length":260,"alphanum_fraction":0.6224507382} {"size":6008,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"\/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and\/or its affiliates. All rights reserved.\nminiob is licensed under Mulan PSL v2.\nYou can use this software according to the terms and conditions of the Mulan PSL v2.\nYou may obtain a copy of Mulan PSL v2 at:\n http:\/\/license.coscl.org.cn\/MulanPSL2\nTHIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\nEITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\nMERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\nSee the Mulan PSL v2 for more details. *\/\n\n\/\/\n\/\/ Created by Longda on 2010\n\/\/\n\n#include \n#include \n\n#include \n\n#include \"common\/conf\/ini.h\"\n#include \"common\/defs.h\"\n#include \"common\/lang\/string.h\"\n#include \"common\/log\/log.h\"\n\nnamespace common {\n\nconst std::string Ini::DEFAULT_SECTION = std::string(\"\");\nconst std::map Ini::empty_map_;\n\nIni::Ini() {}\n\nIni::~Ini() {}\n\nvoid Ini::insert_session(const std::string &session_name) {\n std::map session_map;\n std::pair < std::string, std::map < std::string, std::string >> entry =\n std::pair < std::string, std::map < std::string, std::string\n >> (session_name,\n session_map);\n\n sections_.insert(entry);\n}\n\nstd::map *Ini::switch_session(\n const std::string &session_name) {\n SessionsMap::iterator it = sections_.find(session_name);\n if (it != sections_.end()) {\n return &it->second;\n }\n\n insert_session(session_name);\n\n it = sections_.find(session_name);\n if (it != sections_.end()) {\n return &it->second;\n }\n\n \/\/ should never go this\n return nullptr;\n}\n\nconst std::map &Ini::get(\n const std::string §ion) {\n SessionsMap::iterator it = sections_.find(section);\n if (it == sections_.end()) {\n return empty_map_;\n }\n\n return it->second;\n}\n\nstd::string Ini::get(const std::string &key, const std::string &defaultValue,\n const std::string §ion) {\n std::map section_map = get(section);\n\n std::map::iterator it = section_map.find(key);\n if (it == section_map.end()) {\n return defaultValue;\n }\n\n return it->second;\n}\n\nint Ini::put(const std::string &key, const std::string &value,\n const std::string §ion) {\n std::map *section_map = switch_session(section);\n\n section_map->insert(std::pair(key, value));\n\n return 0;\n}\n\nint Ini::insert_entry(std::map *session_map,\n const std::string &line) {\n if (session_map == nullptr) {\n std::cerr << __FILE__ << __FUNCTION__ << \" session map is null\"\n << std::endl;\n return -1;\n }\n size_t equal_pos = line.find_first_of('=');\n if (equal_pos == std::string::npos) {\n std::cerr << __FILE__ << __FUNCTION__ << \"Invalid configuration line \"\n << line << std::endl;\n return -1;\n }\n\n std::string key = line.substr(0, equal_pos);\n std::string value = line.substr(equal_pos + 1);\n\n strip(key);\n strip(value);\n\n session_map->insert(std::pair(key, value));\n\n return 0;\n}\n\nint Ini::load(const std::string &file_name) {\n std::ifstream ifs;\n\n try {\n\n bool continue_last_line = false;\n\n std::map *current_session =\n switch_session(DEFAULT_SECTION);\n\n char line[MAX_CFG_LINE_LEN];\n\n std::string line_entry;\n\n ifs.open(file_name.c_str());\n while (ifs.good()) {\n\n memset(line, 0, sizeof(line));\n\n ifs.getline(line, sizeof(line));\n\n char *read_buf = strip(line);\n\n if (strlen(read_buf) == 0) {\n \/\/ empty line\n continue;\n }\n\n if (read_buf[0] == CFG_COMMENT_TAG) {\n \/\/ comments line\n continue;\n }\n\n if (read_buf[0] == CFG_SESSION_START_TAG &&\n read_buf[strlen(read_buf) - 1] == CFG_SESSION_END_TAG) {\n\n read_buf[strlen(read_buf) - 1] = '\\0';\n std::string session_name = std::string(read_buf + 1);\n\n current_session = switch_session(session_name);\n\n continue;\n }\n\n if (continue_last_line == false) {\n \/\/ don't need continue last line\n line_entry = read_buf;\n } else {\n line_entry += read_buf;\n }\n\n if (read_buf[strlen(read_buf) - 1] == CFG_CONTINUE_TAG) {\n \/\/ this line isn't finished, need continue\n continue_last_line = true;\n\n \/\/ remove the last character\n line_entry = line_entry.substr(0, line_entry.size() -1);\n continue;\n } else {\n continue_last_line = false;\n insert_entry(current_session, line_entry);\n }\n }\n ifs.close();\n\n file_names_.insert(file_name);\n std::cout << \"Successfully load \" << file_name << std::endl;\n } catch (...) {\n if (ifs.is_open()) {\n ifs.close();\n }\n std::cerr << \"Failed to load \" << file_name << SYS_OUTPUT_ERROR\n << std::endl;\n return -1;\n }\n\n return 0;\n}\n\nvoid Ini::to_string(std::string &output_str) {\n output_str.clear();\n\n output_str += \"Begin dump configuration\\n\";\n\n for (SessionsMap::iterator it = sections_.begin(); it != sections_.end();\n it++) {\n output_str += CFG_SESSION_START_TAG;\n output_str += it->first;\n output_str += CFG_SESSION_END_TAG;\n output_str += \"\\n\";\n\n std::map §ion_map = it->second;\n\n for (std::map::iterator sub_it =\n section_map.begin();\n sub_it != section_map.end(); sub_it++) {\n output_str += sub_it->first;\n output_str += \"=\";\n output_str += sub_it->second;\n output_str += \"\\n\";\n }\n output_str += \"\\n\";\n }\n\n output_str += \"Finish dump configuration \\n\";\n\n return;\n}\n\n\/\/! Accessor function which wraps global properties object\nIni *&get_properties() {\n static Ini *properties = new Ini();\n return properties;\n}\n\n} \/\/namespace common\n","avg_line_length":25.6752136752,"max_line_length":113,"alphanum_fraction":0.6233355526} {"size":8796,"ext":"cpp","lang":"C++","max_stars_count":2.0,"content":"\/******************************************************************************\n\/ LivePresetsExtension\n\/\n\/ Represents a MediaTrack object with data\n\/\n\/ Copyright (c) 2020 and later Dr. med. Frederik Bertling\n\/\n\/\n\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/ of this software and associated documentation files (the \"Software\"), to deal\n\/ in the Software without restriction, including without limitation the rights to\n\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n\/ of the Software, and to permit persons to whom the Software is furnished to\n\/ do so, subject to the following conditions:\n\/\n\/ The above copyright notice and this permission notice shall be included in all\n\/ copies or substantial portions of the Software.\n\/\n\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\n******************************************************************************\/\n\n#include \n#include \n#include \n#include \n\nTrackInfo::TrackInfo(Filterable* parent, MediaTrack *track) : BaseTrackInfo(parent), mGuid(*GetTrackGUID(track)) {\n TrackInfo::saveCurrentState(false);\n}\n\nTrackInfo::TrackInfo(Filterable* parent, ProjectStateContext* ctx) : BaseTrackInfo(parent) {\n initFromChunk(ctx);\n}\n\nTrackInfo::~TrackInfo() {\n for (auto* swSend : mSwSends) {\n delete swSend;\n }\n mSwSends.clear();\n\n for (auto* recFx : mRecFxs) {\n delete recFx;\n }\n mRecFxs.clear();\n}\n\nvoid TrackInfo::saveCurrentState(bool update) {\n BaseTrackInfo::saveCurrentState(update);\n\n char buffer[256];\n GetTrackName(getMediaTrack(), buffer, sizeof(buffer));\n mName = Parameter(this, \"NAME\", buffer, update ? mName.mFilter : RECALLED);\n\n \/\/only manage sends and hardware outputs, receives are automatically created by sends\n BaseTrackInfo::saveSwSendState(nullptr, mSwSends, getMediaTrack(), &mGuid, update);\n BaseTrackInfo::saveHwSendState(nullptr, mHwSends, getMediaTrack(), &mGuid, update);\n BaseTrackInfo::saveFxState(nullptr, mFxs, getMediaTrack(), &mGuid, update, false);\n BaseTrackInfo::saveFxState(nullptr, mRecFxs, getMediaTrack(), &mGuid, update, true);\n}\n\nbool TrackInfo::initFromChunkHandler(std::string& key, std::vector& params) {\n if (key == \"GUID\") {\n stringToGuid(params[0], &mGuid);\n return true;\n }\n if (key == \"NAME\") {\n mName = Parameter(this, \"NAME\", params[0], (FilterMode) std::stoi(params[1]));\n return true;\n }\n return BaseTrackInfo::initFromChunkHandler(key, params);\n}\n\nbool TrackInfo::initFromChunkHandler(std::string &key, ProjectStateContext *ctx) {\n if (key == \"RECFXINFO\") {\n mRecFxs.push_back(new FxInfo(this, ctx));\n return true;\n }\n if (key == \"SWSENDINFO\") {\n mSwSends.push_back(new SwSendInfo(this, ctx));\n return true;\n }\n return BaseTrackInfo::initFromChunkHandler(key, ctx);\n}\n\nvoid TrackInfo::recallSettings() const {\n if (isFilteredInChain())\n return;\n BaseTrackInfo::recallSettings();\n\n \/\/name can only be recalled by SetTrackStateChunk\n\/* if (Merge(filter, mName.mFilter) == RECALLED) {\n char guid[256];\n guidToString(&mGuid, guid);\n std::string chunk = \"\";\n \/\/SetTrackState sets empty values to default value\n SetTrackStateChunk(getMediaTrack(), chunk.data(), false);\n }*\/\n\n \/\/prepare lists for matching sends (that can be reused) and nonMatching sends (that have to be removed)\n auto nonMatchingSends = std::set(mSwSends.begin(), mSwSends.end());\n auto matchingSends = std::vector(GetTrackNumSends(getMediaTrack(), 0));\n\n \/\/go through all sends and check for matching destination because you can't change them\n \/\/remove all obsolete sends, then recall sends beginning with those who have a matching send\n \/\/count backwards that removed tracks dont change other tracks index\n for (int i = GetTrackNumSends(getMediaTrack(), 0) - 1; i >= 0; i--) {\n\n auto dst = (long long) GetTrackSendInfo_Value(getMediaTrack(), 0, i, \"P_DESTTRACK\");\n auto dstTrackGuid = *GetTrackGUID((MediaTrack*) dst);\n\n for (SwSendInfo* sendInfo : nonMatchingSends) {\n if (GuidsEqual(sendInfo->mDstTrackGuid, dstTrackGuid)) {\n matchingSends[i] = sendInfo;\n nonMatchingSends.erase(sendInfo);\n goto matched;\n }\n }\n RemoveTrackSend(getMediaTrack(), 0, i);\n matchingSends.erase(matchingSends.begin() + i);\n matched:;\n }\n\n int index = 0;\n for (const SwSendInfo* send : matchingSends) {\n send->mSendIdx = index;\n send->recallSettings();\n index++;\n }\n for (const SwSendInfo* send : nonMatchingSends) {\n send->mSendIdx = -1;\n send->recallSettings();\n }\n\n \/\/assign input plugin settings\n auto muted = (bool) mParamInfo.at(B_MUTE).mValue;\n if (!muted) {\n for (const auto* recFxInfo : mRecFxs) {\n recFxInfo->recallSettings();\n }\n }\n}\n\nvoid TrackInfo::persistHandler(WDL_FastString &str) const {\n BaseTrackInfo::persistHandler(str);\n\n char dest[64];\n guidToString(&mGuid, dest);\n str.AppendFormatted(4096, \"GUID %s\\n\", dest);\n str.AppendFormatted(4096, \"NAME \\\"%s\\\" %u\\n\", mName.mValue.data(), mName.mFilter);\n\n for (const auto* recFx : mRecFxs) {\n recFx->persist(str);\n }\n\n for (const auto* send : mSwSends) {\n send->persist(str);\n }\n}\n\nMediaTrack* TrackInfo::getMediaTrack() const {\n for (int i = 0; i < CountTracks(nullptr); ++i) {\n MediaTrack* track = GetTrack(nullptr, i);\n if (GuidsEqual(mGuid, *GetTrackGUID(track)))\n return track;\n }\n return nullptr;\n}\n\nstd::set TrackInfo::getKeys() const {\n auto set = BaseTrackInfo::getKeys();\n std::set keys = {\n B_PHASE,\n I_RECARM,\n I_RECINPUT,\n I_RECMODE,\n I_RECMON,\n I_RECMONITEMS,\n I_FOLDERDEPTH,\n I_FOLDERCOMPACT,\n I_PANMODE,\n D_PANLAW,\n B_SHOWINMIXER,\n B_SHOWINTCP,\n B_MAINSEND,\n C_MAINSEND_OFFS,\n B_FREEMODE,\n };\n\n set.insert(keys.begin(),keys.end());\n return set;\n}\n\nchar * TrackInfo::getTreeText() const {\n std::string newText = getFilterText() + \" Track: \" + mName.mValue;\n newText.copy(mTreeText, newText.length());\n mTreeText[newText.length()] = '\\0';\n return mTreeText;\n}\n\nstd::string TrackInfo::getChunkId() const {\n return \"TRACKINFO\";\n}\n\nFilterPreset* TrackInfo::extractFilterPreset() {\n FilterPreset::ItemIdentifier id{};\n id.guid = mGuid;\n\n auto childs = std::vector();\n\n childs.push_back(mParamInfo.extractFilterPreset());\n childs.push_back(mName.extractFilterPreset());\n for (auto* swSend : mSwSends) {\n childs.push_back(swSend->extractFilterPreset());\n }\n for (auto* hwSend : mHwSends) {\n childs.push_back(hwSend->extractFilterPreset());\n }\n for (auto* fx : mFxs) {\n childs.push_back(fx->extractFilterPreset());\n }\n for (auto* recFx : mRecFxs) {\n childs.push_back(recFx->extractFilterPreset());\n }\n\n return new FilterPreset(id, TRACK, mFilter, childs);}\n\nbool TrackInfo::applyFilterPreset(FilterPreset *preset) {\n if (preset->mType == TRACK && GuidsEqual(preset->mId.guid, mGuid)) {\n mFilter = preset->mFilter;\n\n auto toFilters = std::set();\n toFilters.insert((Filterable*) &mParamInfo);\n toFilters.insert((Filterable*) &mName);\n toFilters.insert(mSwSends.begin(), mSwSends.end());\n toFilters.insert(mHwSends.begin(), mHwSends.end());\n toFilters.insert(mFxs.begin(), mFxs.end());\n toFilters.insert(mRecFxs.begin(), mRecFxs.end());\n\n for (auto* child : preset->mChilds) {\n for (auto* toFilter : toFilters) {\n if (toFilter->applyFilterPreset(child)) {\n toFilters.erase(toFilter);\n goto cnt;\n }\n }\n cnt:;\n }\n return true;\n }\n return false;}","avg_line_length":34.0930232558,"max_line_length":114,"alphanum_fraction":0.6333560709} {"size":23254,"ext":"cxx","lang":"C++","max_stars_count":null,"content":"\/*=========================================================================\r\n\r\n Program: Visualization Toolkit\r\n Module: vtkStreamer.cxx\r\n\r\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\r\n All rights reserved.\r\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\r\n\r\n This software is distributed WITHOUT ANY WARRANTY; without even\r\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n PURPOSE. See the above copyright notice for more information.\r\n\r\n=========================================================================*\/\r\n#include \"vtkStreamer.h\"\r\n\r\n#include \"vtkCell.h\"\r\n#include \"vtkDataSet.h\"\r\n#include \"vtkDoubleArray.h\"\r\n#include \"vtkExecutive.h\"\r\n#include \"vtkGenericCell.h\"\r\n#include \"vtkInformation.h\"\r\n#include \"vtkInterpolatedVelocityField.h\"\r\n#include \"vtkMath.h\"\r\n#include \"vtkMultiThreader.h\"\r\n#include \"vtkObjectFactory.h\"\r\n#include \"vtkPointData.h\"\r\n#include \"vtkRungeKutta2.h\"\r\n\r\nvtkCxxSetObjectMacro(vtkStreamer,Integrator,vtkInitialValueProblemSolver);\r\n\r\n#define VTK_START_FROM_POSITION 0\r\n#define VTK_START_FROM_LOCATION 1\r\n\r\nstatic const double VTK_EPSILON=1E-12;\r\n\r\nstruct vtkStreamerThreadStruct\r\n{\r\n vtkStreamer *Filter;\r\n vtkDataSet *Input;\r\n vtkDataSet *Source;\r\n};\r\n\r\nvtkStreamer::StreamArray::StreamArray()\r\n{\r\n this->MaxId = -1;\r\n this->Array = new vtkStreamer::StreamPoint[1000];\r\n this->Size = 1000;\r\n this->Extend = 5000;\r\n this->Direction = VTK_INTEGRATE_FORWARD;\r\n}\r\n\r\nvtkStreamer::StreamPoint *vtkStreamer::StreamArray::Resize(vtkIdType sz)\r\n{\r\n vtkStreamer::StreamPoint *newArray;\r\n vtkIdType newSize;\r\n\r\n if (sz >= this->Size)\r\n {\r\n newSize = this->Size +\r\n this->Extend*(((sz-this->Size)\/this->Extend)+1);\r\n }\r\n else\r\n {\r\n newSize = sz;\r\n }\r\n\r\n newArray = new vtkStreamer::StreamPoint[newSize];\r\n\r\n memcpy(newArray, this->Array,\r\n static_cast(sz < this->Size ? sz : this->Size)\r\n * sizeof(vtkStreamer::StreamPoint));\r\n\r\n this->Size = newSize;\r\n delete [] this->Array;\r\n this->Array = newArray;\r\n\r\n return this->Array;\r\n}\r\n\r\n\/\/ Construct object to start from position (0,0,0); integrate forward; terminal\r\n\/\/ speed 0.0; vorticity computation off; integrations step length 0.2; and\r\n\/\/ maximum propagation time 100.0.\r\nvtkStreamer::vtkStreamer()\r\n{\r\n this->StartFrom = VTK_START_FROM_POSITION;\r\n\r\n this->StartCell = 0;\r\n this->StartSubId = 0;\r\n this->StartPCoords[0] = this->StartPCoords[1] = this->StartPCoords[2] = 0.5;\r\n this->StartPosition[0] = this->StartPosition[1] = this->StartPosition[2] = 0.0;\r\n this->Streamers = NULL;\r\n this->MaximumPropagationTime = 100.0;\r\n this->IntegrationDirection = VTK_INTEGRATE_FORWARD;\r\n this->IntegrationStepLength = 0.2;\r\n this->Vorticity = 0;\r\n this->TerminalSpeed = 0.0;\r\n this->SpeedScalars = 0;\r\n this->OrientationScalars = 0;\r\n this->NumberOfStreamers = 0;\r\n this->Epsilon=VTK_EPSILON;\r\n\r\n this->Threader = vtkMultiThreader::New();\r\n this->NumberOfThreads = this->Threader->GetNumberOfThreads();\r\n this->Integrator = vtkRungeKutta2::New();\r\n this->SavePointInterval = 0.00001;\r\n\r\n this->SetNumberOfInputPorts(2);\r\n}\r\n\r\nvtkStreamer::~vtkStreamer()\r\n{\r\n delete [] this->Streamers;\r\n\r\n if (this->Threader)\r\n {\r\n this->Threader->Delete();\r\n }\r\n this->SetIntegrator(0);\r\n}\r\n\r\nvoid vtkStreamer::SetSourceConnection(vtkAlgorithmOutput* algOutput)\r\n{\r\n this->SetInputConnection(1,algOutput);\r\n}\r\n\r\nvoid vtkStreamer::SetSourceData(vtkDataSet *source)\r\n{\r\n this->SetInputData(1, source);\r\n}\r\n\r\nvtkDataSet *vtkStreamer::GetSource()\r\n{\r\n if (this->GetNumberOfInputConnections(1) < 1)\r\n {\r\n return NULL;\r\n }\r\n return vtkDataSet::SafeDownCast(\r\n this->GetExecutive()->GetInputData(1, 0));\r\n}\r\n\r\n\/\/ Specify the start of the streamline in the cell coordinate system. That is,\r\n\/\/ cellId and subId (if composite cell), and parametric coordinates.\r\nvoid vtkStreamer::SetStartLocation(vtkIdType cellId, int subId,\r\n double pcoords[3])\r\n{\r\n if ( cellId != this->StartCell || subId != this->StartSubId ||\r\n pcoords[0] != this->StartPCoords[0] ||\r\n pcoords[1] != this->StartPCoords[1] ||\r\n pcoords[2] != this->StartPCoords[2] )\r\n {\r\n this->Modified();\r\n this->StartFrom = VTK_START_FROM_LOCATION;\r\n\r\n this->StartCell = cellId;\r\n this->StartSubId = subId;\r\n this->StartPCoords[0] = pcoords[0];\r\n this->StartPCoords[1] = pcoords[1];\r\n this->StartPCoords[2] = pcoords[2];\r\n }\r\n}\r\n\r\n\/\/ Specify the start of the streamline in the cell coordinate system. That is,\r\n\/\/ cellId and subId (if composite cell), and parametric coordinates.\r\nvoid vtkStreamer::SetStartLocation(vtkIdType cellId, int subId, double r,\r\n double s, double t)\r\n{\r\n double pcoords[3];\r\n pcoords[0] = r;\r\n pcoords[1] = s;\r\n pcoords[2] = t;\r\n\r\n this->SetStartLocation(cellId, subId, pcoords);\r\n}\r\n\r\n\/\/ Get the starting location of the streamline in the cell coordinate system.\r\nvtkIdType vtkStreamer::GetStartLocation(int& subId, double pcoords[3])\r\n{\r\n subId = this->StartSubId;\r\n pcoords[0] = this->StartPCoords[0];\r\n pcoords[1] = this->StartPCoords[1];\r\n pcoords[2] = this->StartPCoords[2];\r\n return this->StartCell;\r\n}\r\n\r\n\/\/ Specify the start of the streamline in the global coordinate system. Search\r\n\/\/ must be performed to find initial cell to start integration from.\r\nvoid vtkStreamer::SetStartPosition(double x[3])\r\n{\r\n if ( x[0] != this->StartPosition[0] || x[1] != this->StartPosition[1] ||\r\n x[2] != this->StartPosition[2] )\r\n {\r\n this->Modified();\r\n this->StartFrom = VTK_START_FROM_POSITION;\r\n\r\n this->StartPosition[0] = x[0];\r\n this->StartPosition[1] = x[1];\r\n this->StartPosition[2] = x[2];\r\n }\r\n}\r\n\r\n\/\/ Specify the start of the streamline in the global coordinate system. Search\r\n\/\/ must be performed to find initial cell to start integration from.\r\nvoid vtkStreamer::SetStartPosition(double x, double y, double z)\r\n{\r\n double pos[3];\r\n pos[0] = x;\r\n pos[1] = y;\r\n pos[2] = z;\r\n\r\n this->SetStartPosition(pos);\r\n}\r\n\r\n\/\/ Get the start position in global x-y-z coordinates.\r\ndouble *vtkStreamer::GetStartPosition()\r\n{\r\n return this->StartPosition;\r\n}\r\n\r\nVTK_THREAD_RETURN_TYPE vtkStreamer::ThreadedIntegrate( void *arg )\r\n{\r\n vtkStreamer *self;\r\n vtkStreamerThreadStruct *str;\r\n int thread_count;\r\n int thread_id;\r\n vtkStreamer::StreamArray *streamer;\r\n vtkStreamer::StreamPoint *sNext = 0, *sPtr;\r\n vtkStreamer::StreamPoint pt1, pt2;\r\n int i;\r\n vtkIdType idxNext, ptId;\r\n double d, step, dir;\r\n double xNext[3], vel[3];\r\n double *cellVel;\r\n double derivs[9];\r\n double pcoords[3];\r\n double coords[4];\r\n vtkDataSet *input;\r\n vtkGenericCell *cell;\r\n vtkPointData *pd;\r\n vtkDataArray *inScalars;\r\n vtkDataArray *inVectors;\r\n vtkDoubleArray *cellVectors;\r\n vtkDataArray *cellScalars=0;\r\n double tOffset, vort[3];\r\n double err;\r\n int counter=0;\r\n\r\n vtkMultiThreader::ThreadInfo *info=\r\n static_cast(arg);\r\n\r\n thread_id = info->ThreadID;\r\n thread_count = info->NumberOfThreads;\r\n str = static_cast(info->UserData);\r\n self = str->Filter;\r\n\r\n input = str->Input;\r\n pd = input->GetPointData();\r\n inScalars = pd->GetScalars();\r\n inVectors = pd->GetVectors();\r\n\r\n cell = vtkGenericCell::New();\r\n cellVectors = vtkDoubleArray::New();\r\n cellVectors->SetNumberOfComponents(3);\r\n cellVectors->Allocate(3*VTK_CELL_SIZE);\r\n if (inScalars)\r\n {\r\n cellScalars = inScalars->NewInstance();\r\n cellScalars->SetNumberOfComponents(inScalars->GetNumberOfComponents());\r\n cellScalars->Allocate(inScalars->GetNumberOfComponents()*VTK_CELL_SIZE);\r\n }\r\n\r\n \/\/ Set the function set to be integrated\r\n vtkInterpolatedVelocityField* func = vtkInterpolatedVelocityField::New();\r\n func->AddDataSet(input);\r\n\r\n if (self->GetIntegrator() == 0)\r\n {\r\n vtkGenericWarningMacro(\"No integrator is specified.\");\r\n return VTK_THREAD_RETURN_VALUE;\r\n }\r\n\r\n double *w = new double[input->GetMaxCellSize()];\r\n\r\n \/\/ Create a new integrator, the type is the same as Integrator\r\n vtkInitialValueProblemSolver* integrator =\r\n self->GetIntegrator()->NewInstance();\r\n integrator->SetFunctionSet(func);\r\n\r\n \/\/ Used to avoid calling these function many times during\r\n \/\/ the integration\r\n double termspeed = self->GetTerminalSpeed();\r\n double maxtime = self->GetMaximumPropagationTime();\r\n double savePointInterval = self->GetSavePointInterval();\r\n\r\n \/\/ For each streamer, integrate in appropriate direction\r\n \/\/ Do only the streamers that this thread should handle.\r\n for (ptId=0; ptId < self->GetNumberOfStreamers(); ptId++)\r\n {\r\n if ( ptId % thread_count == thread_id )\r\n {\r\n \/\/ Get starting step\r\n streamer = self->GetStreamers() + ptId;\r\n sPtr = streamer->GetStreamPoint(0);\r\n if ( sPtr->cellId < 0 )\r\n {\r\n continue;\r\n }\r\n \/\/ Set the last cell id in the vtkInterpolatedVelocityField\r\n \/\/ object to speed up FindCell calls\r\n func->SetLastCellId(sPtr->cellId);\r\n\r\n dir = streamer->Direction;\r\n\r\n \/\/ Copy the first point\r\n pt1 = *sPtr;\r\n pt2 = *sPtr;\r\n tOffset = pt1.t;\r\n\r\n \/\/integrate until time has been exceeded\r\n while ( pt1.cellId >= 0 && pt1.speed > termspeed && pt1.t < maxtime )\r\n {\r\n\r\n if ( counter++ % 1000 == 0 )\r\n {\r\n if (!thread_id)\r\n {\r\n self->UpdateProgress(\r\n static_cast(ptId)\r\n \/static_cast(self->GetNumberOfStreamers())\r\n +pt1.t\/maxtime\/static_cast(self->GetNumberOfStreamers()));\r\n }\r\n if (self->GetAbortExecute())\r\n {\r\n break;\r\n }\r\n }\r\n\r\n \/\/ Set the integration step to be characteristic cell length\r\n \/\/ time IntegrationStepLength\r\n input->GetCell(pt1.cellId, cell);\r\n step = dir*self->GetIntegrationStepLength()\r\n * sqrt(static_cast(cell->GetLength2()))\/pt1.speed;\r\n\r\n \/\/ Calculate the next step using the integrator provided\r\n if (integrator->ComputeNextStep(pt1.x, pt1.v, xNext, 0, step, 0, err)\r\n != 0)\r\n {\r\n break;\r\n }\r\n\r\n for(i=0; i<3; i++)\r\n {\r\n coords[i] = xNext[i];\r\n }\r\n\r\n \/\/ Interpolate the velocity field at coords\r\n if ( !func->FunctionValues(coords, vel) )\r\n {\r\n break;\r\n }\r\n\r\n for(i=0; i<3; i++)\r\n {\r\n pt2.v[i] = vel[i];\r\n }\r\n\r\n for (i=0; i<3; i++)\r\n {\r\n pt2.x[i] = xNext[i];\r\n }\r\n\r\n pt2.cellId = func->GetLastCellId();\r\n func->GetLastWeights(w);\r\n func->GetLastLocalCoordinates(pcoords);\r\n input->GetCell(pt2.cellId, cell);\r\n\r\n if ( inScalars )\r\n {\r\n \/\/ Interpolate scalars\r\n inScalars->GetTuples(cell->PointIds, cellScalars);\r\n for (pt2.s=0.0, i=0; i < cell->GetNumberOfPoints(); i++)\r\n {\r\n pt2.s += cellScalars->GetComponent(i,0) * w[i];\r\n }\r\n }\r\n\r\n pt2.speed = vtkMath::Norm(pt2.v);\r\n\r\n d = sqrt(static_cast(\r\n vtkMath::Distance2BetweenPoints(pt1.x,pt2.x)));\r\n pt2.d = pt1.d + d;\r\n \/\/ If at stagnation region, stop the integration\r\n if ( d <= self->Epsilon || (pt1.speed + pt2.speed) <= self->Epsilon)\r\n {\r\n pt2.t = pt1.t;\r\n break;\r\n }\r\n pt2.t = pt1.t + (2.0 * d \/ (pt1.speed + pt2.speed));\r\n\r\n if (self->GetVorticity() && inVectors)\r\n {\r\n \/\/ compute vorticity\r\n inVectors->GetTuples(cell->PointIds, cellVectors);\r\n cellVel = cellVectors->GetPointer(0);\r\n cell->Derivatives(0, pcoords, cellVel, 3, derivs);\r\n vort[0] = derivs[7] - derivs[5];\r\n vort[1] = derivs[2] - derivs[6];\r\n vort[2] = derivs[3] - derivs[1];\r\n \/\/ rotation\r\n pt2.omega = vtkMath::Dot(vort, pt2.v);\r\n pt2.omega \/= pt2.speed;\r\n pt2.theta += (pt1.omega+pt2.omega)\/2 * (pt2.t - pt1.t);\r\n }\r\n\r\n\r\n \/\/ Store only points which have a point to be displayed\r\n \/\/ between them\r\n if (tOffset >= pt1.t && tOffset <= pt2.t)\r\n {\r\n \/\/ Do not store if same as the last point.\r\n \/\/ To avoid storing some points twice.\r\n if ( !sNext || sNext->x[0] != pt1.x[0] || sNext->x[1] != pt1.x[1]\r\n || sNext->x[2] != pt1.x[2] )\r\n {\r\n idxNext = streamer->InsertNextStreamPoint();\r\n sNext = streamer->GetStreamPoint(idxNext);\r\n *sNext = pt1;\r\n }\r\n idxNext = streamer->InsertNextStreamPoint();\r\n sNext = streamer->GetStreamPoint(idxNext);\r\n *sNext = pt2;\r\n }\r\n if (tOffset < pt2.t)\r\n {\r\n tOffset += (static_cast(\r\n ( pt2.t - tOffset) \/ savePointInterval)\r\n + 1) * savePointInterval;\r\n }\r\n pt1 = pt2;\r\n\r\n }\r\n \/\/ Store the last point anyway.\r\n if ( !sNext || sNext->x[0] != pt2.x[0] || sNext->x[1] != pt2.x[1]\r\n || sNext->x[2] != pt2.x[2] )\r\n {\r\n idxNext = streamer->InsertNextStreamPoint();\r\n sNext = streamer->GetStreamPoint(idxNext);\r\n *sNext = pt2;\r\n }\r\n \/\/ Clear the last cell to avoid starting a search from\r\n \/\/ the last point in the streamline\r\n func->ClearLastCellId();\r\n }\r\n }\r\n\r\n integrator->Delete();\r\n func->Delete();\r\n\r\n cell->Delete();\r\n cellVectors->Delete();\r\n if (cellScalars)\r\n {\r\n cellScalars->Delete();\r\n }\r\n delete[] w;\r\n\r\n return VTK_THREAD_RETURN_VALUE;\r\n}\r\n\r\nvoid vtkStreamer::Integrate(vtkDataSet *input, vtkDataSet *source)\r\n{\r\n vtkPointData *pd = input->GetPointData();\r\n vtkDataArray *inScalars;\r\n vtkDataArray *inVectors;\r\n vtkIdType numSourcePts, idx, idxNext;\r\n vtkStreamer::StreamPoint *sNext, *sPtr;\r\n vtkIdType ptId, i;\r\n int j, offset;\r\n vtkCell *cell;\r\n double v[3], *cellVel, derivs[9], xNext[3], vort[3];\r\n double tol2;\r\n double *w = new double[input->GetMaxCellSize()];\r\n vtkDoubleArray *cellVectors;\r\n vtkDataArray *cellScalars=0;\r\n\r\n vtkDebugMacro(<<\"Generating streamers\");\r\n this->NumberOfStreamers = 0;\r\n\r\n \/\/ reexecuting - delete old stuff\r\n delete [] this->Streamers;\r\n this->Streamers = NULL;\r\n\r\n if ( ! (inVectors=pd->GetVectors()) )\r\n {\r\n delete [] w;\r\n vtkErrorMacro(<<\"No vector data defined!\");\r\n return;\r\n }\r\n\r\n cellVectors = vtkDoubleArray::New();\r\n cellVectors->SetNumberOfComponents(3);\r\n cellVectors->Allocate(3*VTK_CELL_SIZE);\r\n\r\n inScalars = pd->GetScalars();\r\n\r\n if (inScalars)\r\n {\r\n cellScalars = inScalars->NewInstance();\r\n cellScalars->SetNumberOfComponents(inScalars->GetNumberOfComponents());\r\n cellScalars->Allocate(cellScalars->GetNumberOfComponents()*VTK_CELL_SIZE);\r\n }\r\n\r\n tol2 = input->GetLength()\/1000;\r\n tol2 = tol2*tol2;\r\n\r\n \/\/\r\n \/\/ Create starting points\r\n \/\/\r\n this->NumberOfStreamers = numSourcePts = offset = 1;\r\n if ( source )\r\n {\r\n this->NumberOfStreamers = numSourcePts = source->GetNumberOfPoints();\r\n }\r\n\r\n if ( this->IntegrationDirection == VTK_INTEGRATE_BOTH_DIRECTIONS )\r\n {\r\n offset = 2;\r\n this->NumberOfStreamers *= 2;\r\n }\r\n\r\n this->Streamers = new vtkStreamer::StreamArray[this->NumberOfStreamers];\r\n\r\n if ( this->StartFrom == VTK_START_FROM_POSITION && !source )\r\n {\r\n idx = this->Streamers[0].InsertNextStreamPoint();\r\n sPtr = this->Streamers[0].GetStreamPoint(idx);\r\n sPtr->subId = 0;\r\n for (i=0; i<3; i++)\r\n {\r\n sPtr->x[i] = this->StartPosition[i];\r\n }\r\n sPtr->cellId = input->FindCell(this->StartPosition, NULL, -1, 0.0,\r\n sPtr->subId, sPtr->p, w);\r\n }\r\n\r\n else if ( this->StartFrom == VTK_START_FROM_LOCATION && !source )\r\n {\r\n idx = this->Streamers[0].InsertNextStreamPoint();\r\n sPtr = this->Streamers[0].GetStreamPoint(idx);\r\n sPtr->subId = 0;\r\n cell = input->GetCell(sPtr->cellId);\r\n cell->EvaluateLocation(sPtr->subId, sPtr->p, sPtr->x, w);\r\n }\r\n\r\n else \/\/VTK_START_FROM_SOURCE\r\n {\r\n for (ptId=0; ptId < numSourcePts; ptId++)\r\n {\r\n idx = this->Streamers[offset*ptId].InsertNextStreamPoint();\r\n sPtr = this->Streamers[offset*ptId].GetStreamPoint(idx);\r\n sPtr->subId = 0;\r\n source->GetPoint(ptId,sPtr->x);\r\n sPtr->cellId = input->FindCell(sPtr->x, NULL, -1, tol2,\r\n sPtr->subId, sPtr->p, w);\r\n }\r\n }\r\n\r\n \/\/ Finish initializing each streamer\r\n \/\/\r\n for (idx=0, ptId=0; ptId < numSourcePts; ptId++)\r\n {\r\n this->Streamers[offset*ptId].Direction = 1.0;\r\n sPtr = this->Streamers[offset*ptId].GetStreamPoint(idx);\r\n sPtr->d = 0.0;\r\n sPtr->t = 0.0;\r\n sPtr->s = 0.0;\r\n sPtr->theta = 0.0;\r\n sPtr->omega = 0.0;\r\n\r\n if ( sPtr->cellId >= 0 ) \/\/starting point in dataset\r\n {\r\n cell = input->GetCell(sPtr->cellId);\r\n cell->EvaluateLocation(sPtr->subId, sPtr->p, xNext, w);\r\n\r\n inVectors->GetTuples(cell->PointIds, cellVectors);\r\n sPtr->v[0] = sPtr->v[1] = sPtr->v[2] = 0.0;\r\n for (i=0; i < cell->GetNumberOfPoints(); i++)\r\n {\r\n cellVectors->GetTuple(i, v);\r\n for (j=0; j<3; j++)\r\n {\r\n sPtr->v[j] += v[j] * w[i];\r\n }\r\n }\r\n\r\n sPtr->speed = vtkMath::Norm(sPtr->v);\r\n\r\n if (this->GetVorticity() && inVectors)\r\n {\r\n \/\/ compute vorticity\r\n inVectors->GetTuples(cell->PointIds, cellVectors);\r\n cellVel = cellVectors->GetPointer(0);\r\n cell->Derivatives(0, sPtr->p, cellVel, 3, derivs);\r\n vort[0] = derivs[7] - derivs[5];\r\n vort[1] = derivs[2] - derivs[6];\r\n vort[2] = derivs[3] - derivs[1];\r\n \/\/ rotation\r\n sPtr->omega = vtkMath::Dot(vort, sPtr->v);\r\n sPtr->omega \/= sPtr->speed;\r\n sPtr->theta = 0;\r\n }\r\n\r\n if ( inScalars )\r\n {\r\n inScalars->GetTuples(cell->PointIds, cellScalars);\r\n for (sPtr->s=0, i=0; i < cell->GetNumberOfPoints(); i++)\r\n {\r\n sPtr->s += cellScalars->GetComponent(i,0) * w[i];\r\n }\r\n }\r\n }\r\n else\r\n {\r\n for (j=0; j<3; j++)\r\n {\r\n sPtr->p[j] = 0.0;\r\n sPtr->v[j] = 0.0;\r\n }\r\n sPtr->speed = 0;\r\n }\r\n\r\n if ( this->IntegrationDirection == VTK_INTEGRATE_BOTH_DIRECTIONS )\r\n {\r\n this->Streamers[offset*ptId+1].Direction = -1.0;\r\n idxNext = this->Streamers[offset*ptId+1].InsertNextStreamPoint();\r\n sNext = this->Streamers[offset*ptId+1].GetStreamPoint(idxNext);\r\n sPtr = this->Streamers[offset*ptId].GetStreamPoint(idx);\r\n *sNext = *sPtr;\r\n }\r\n else if ( this->IntegrationDirection == VTK_INTEGRATE_BACKWARD )\r\n {\r\n this->Streamers[offset*ptId].Direction = -1.0;\r\n }\r\n\r\n\r\n } \/\/for each streamer\r\n\r\n \/\/ Some data access methods must be called once from a single thread before they\r\n \/\/ can safely be used. Call those now\r\n vtkGenericCell *gcell = vtkGenericCell::New();\r\n input->GetCell(0,gcell);\r\n gcell->Delete();\r\n\r\n \/\/ Set up and execute the thread\r\n this->Threader->SetNumberOfThreads( this->NumberOfThreads );\r\n vtkStreamerThreadStruct str;\r\n str.Filter = this;\r\n str.Input = input;\r\n str.Source = source;\r\n this->Threader->SetSingleMethod( vtkStreamer::ThreadedIntegrate, &str );\r\n this->Threader->SingleMethodExecute();\r\n\r\n \/\/\r\n \/\/ Now create appropriate representation\r\n \/\/\r\n if ( this->OrientationScalars && !this->SpeedScalars)\r\n {\r\n for (ptId=0; ptId < this->NumberOfStreamers; ptId++)\r\n {\r\n for ( sPtr=this->Streamers[ptId].GetStreamPoint(0), i=0;\r\n i < this->Streamers[ptId].GetNumberOfPoints() && sPtr->cellId >= 0;\r\n i++, sPtr=this->Streamers[ptId].GetStreamPoint(i) )\r\n {\r\n sPtr->s = sPtr->theta;\r\n }\r\n }\r\n }\r\n\r\n if ( this->SpeedScalars )\r\n {\r\n for (ptId=0; ptId < this->NumberOfStreamers; ptId++)\r\n {\r\n for ( sPtr=this->Streamers[ptId].GetStreamPoint(0), i=0;\r\n i < this->Streamers[ptId].GetNumberOfPoints() && sPtr->cellId >= 0;\r\n i++, sPtr=this->Streamers[ptId].GetStreamPoint(i) )\r\n {\r\n sPtr->s = sPtr->speed;\r\n }\r\n }\r\n }\r\n delete [] w;\r\n cellVectors->Delete();\r\n if (cellScalars)\r\n {\r\n cellScalars->Delete();\r\n }\r\n}\r\n\r\nint vtkStreamer::FillInputPortInformation(int port, vtkInformation *info)\r\n{\r\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkDataSet\");\r\n\r\n if (port == 1)\r\n {\r\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\r\n }\r\n return 1;\r\n}\r\n\r\nvoid vtkStreamer::PrintSelf(ostream& os, vtkIndent indent)\r\n{\r\n this->Superclass::PrintSelf(os,indent);\r\n\r\n if ( this->StartFrom == VTK_START_FROM_POSITION && !this->GetSource())\r\n {\r\n os << indent << \"Starting Position: (\" << this->StartPosition[0] << \",\"\r\n << this->StartPosition[1] << \", \" << this->StartPosition[2] << \")\\n\";\r\n }\r\n else if ( this->StartFrom == VTK_START_FROM_LOCATION && !this->GetSource())\r\n {\r\n os << indent << \"Starting Location:\\n\\tCell: \" << this->StartCell\r\n << \"\\n\\tSubId: \" << this->StartSubId << \"\\n\\tP.Coordinates: (\"\r\n << this->StartPCoords[0] << \", \"\r\n << this->StartPCoords[1] << \", \"\r\n << this->StartPCoords[2] << \")\\n\";\r\n }\r\n else\r\n {\r\n os << indent << \"Starting Source: \"\r\n << static_cast(this->GetSource()) << \"\\n\";\r\n }\r\n\r\n os << indent << \"Maximum Propagation Time: \"\r\n << this->MaximumPropagationTime << \"\\n\";\r\n\r\n if ( this->IntegrationDirection == VTK_INTEGRATE_FORWARD )\r\n {\r\n os << indent << \"Integration Direction: FORWARD\\n\";\r\n }\r\n else if ( this->IntegrationDirection == VTK_INTEGRATE_BACKWARD )\r\n {\r\n os << indent << \"Integration Direction: BACKWARD\\n\";\r\n }\r\n else\r\n {\r\n os << indent << \"Integration Direction: FORWARD & BACKWARD\\n\";\r\n }\r\n\r\n os << indent << \"Integration Step Length: \" << this->IntegrationStepLength << \"\\n\";\r\n\r\n os << indent << \"Vorticity: \" << (this->Vorticity ? \"On\\n\" : \"Off\\n\");\r\n\r\n os << indent << \"Terminal Speed: \" << this->TerminalSpeed << \"\\n\";\r\n\r\n os << indent << \"Speed Scalars: \" << (this->SpeedScalars ? \"On\\n\" : \"Off\\n\");\r\n\r\n os << indent << \"Orientation Scalars: \" << (this->OrientationScalars ? \"On\\n\" : \"Off\\n\");\r\n\r\n os << indent << \"Interval with which points are stored:\"\r\n << this->SavePointInterval << endl;\r\n\r\n os << indent << \"Integrator: \" << this->Integrator << endl;\r\n\r\n os << indent << \"Number Of Streamers: \" << this->NumberOfStreamers << \"\\n\";\r\n os << indent << \"Number Of Threads: \" << this->NumberOfThreads << \"\\n\";\r\n os << indent << \"Epsilon: \" << this->Epsilon << \"\\n\";\r\n}\r\n","avg_line_length":30.2786458333,"max_line_length":92,"alphanum_fraction":0.5790401651} {"size":1799,"ext":"hpp","lang":"C++","max_stars_count":null,"content":"\/*\n *\n * SHA512\n *\n * Created by El Khalil Bellakrid on 02\/04\/2019.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#pragma once\n\n#include \n#include \n\nnamespace ledger {\n namespace core {\n class SHA512 {\n public:\n static std::string stringToHexHash(const std::string& input);\n static std::string bytesToHexHash(const std::vector& bytes);\n static std::vector stringToBytesHash(const std::string& input);\n static std::vector bytesToBytesHash(const std::vector& bytes);\n\n private:\n static std::vector dataToBytesHash(const void *data, size_t size);\n };\n }\n}","avg_line_length":36.7142857143,"max_line_length":92,"alphanum_fraction":0.7103946637} {"size":34791,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/*\n * Copyright 2018 Andrei Pangin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"flightRecorder.h\"\n#include \"jfrMetadata.h\"\n#include \"dictionary.h\"\n#include \"log.h\"\n#include \"os.h\"\n#include \"profiler.h\"\n#include \"threadFilter.h\"\n#include \"vmStructs.h\"\n\n\nstatic const unsigned char JFR_COMBINER_CLASS[] = {\n#include \"helper\/one\/profiler\/JfrCombiner.class.h\"\n};\n\n\nconst int BUFFER_SIZE = 1024;\nconst int BUFFER_LIMIT = BUFFER_SIZE - 128;\nconst int RECORDING_BUFFER_SIZE = 65536;\nconst int RECORDING_BUFFER_LIMIT = RECORDING_BUFFER_SIZE - 4096;\nconst int MAX_STRING_LENGTH = 8191;\n\n\nstatic const char* const SETTING_RING[] = {NULL, \"kernel\", \"user\"};\nstatic const char* const SETTING_CSTACK[] = {NULL, \"no\", \"fp\", \"lbr\"};\n\n\nenum FrameTypeId {\n FRAME_INTERPRETED = 0,\n FRAME_JIT_COMPILED = 1,\n FRAME_INLINED = 2,\n FRAME_NATIVE = 3,\n FRAME_CPP = 4,\n FRAME_KERNEL = 5,\n};\n\n\nstruct CpuTime {\n u64 real;\n u64 user;\n u64 system;\n};\n\nstruct CpuTimes {\n CpuTime proc;\n CpuTime total;\n};\n\n\nclass MethodInfo {\n public:\n MethodInfo() : _key(0) {\n }\n\n u32 _key;\n u32 _class;\n u32 _name;\n u32 _sig;\n jint _modifiers;\n jint _line_number_table_size;\n jvmtiLineNumberEntry* _line_number_table;\n FrameTypeId _type;\n\n jint getLineNumber(jint bci) {\n if (_line_number_table_size == 0) {\n return 0;\n }\n\n int i = 1;\n while (i < _line_number_table_size && bci >= _line_number_table[i].start_location) {\n i++;\n }\n return _line_number_table[i - 1].line_number;\n }\n};\n\n\nclass Buffer {\n private:\n int _offset;\n char _data[BUFFER_SIZE - sizeof(int)];\n\n public:\n Buffer() : _offset(0) {\n }\n\n const char* data() const {\n return _data;\n }\n\n int offset() const {\n return _offset;\n }\n\n int skip(int delta) {\n int offset = _offset;\n _offset = offset + delta;\n return offset;\n }\n\n void reset() {\n _offset = 0;\n }\n\n void put(const char* v, u32 len) {\n memcpy(_data + _offset, v, len);\n _offset += (int)len;\n }\n\n void put8(char v) {\n _data[_offset++] = v;\n }\n\n void put16(short v) {\n *(short*)(_data + _offset) = htons(v);\n _offset += 2;\n }\n\n void put32(int v) {\n *(int*)(_data + _offset) = htonl(v);\n _offset += 4;\n }\n\n void put64(u64 v) {\n *(u64*)(_data + _offset) = OS::hton64(v);\n _offset += 8;\n }\n\n void putFloat(float v) {\n union {\n float f;\n int i;\n } u;\n\n u.f = v;\n put32(u.i);\n }\n\n void putVar32(u32 v) {\n while (v > 0x7f) {\n _data[_offset++] = (char)v | 0x80;\n v >>= 7;\n }\n _data[_offset++] = (char)v;\n }\n\n void putVar64(u64 v) {\n int iter = 0;\n while (v > 0x1fffff) {\n _data[_offset++] = (char)v | 0x80; v >>= 7;\n _data[_offset++] = (char)v | 0x80; v >>= 7;\n _data[_offset++] = (char)v | 0x80; v >>= 7;\n if (++iter == 3) return;\n }\n while (v > 0x7f) {\n _data[_offset++] = (char)v | 0x80;\n v >>= 7;\n }\n _data[_offset++] = (char)v;\n }\n\n void putUtf8(const char* v) {\n if (v == NULL) {\n put8(0);\n } else {\n putUtf8(v, strlen(v) & MAX_STRING_LENGTH);\n }\n }\n\n void putUtf8(const char* v, u32 len) {\n put8(3);\n putVar32(len);\n put(v, len);\n }\n\n void put8(int offset, char v) {\n _data[offset] = v;\n }\n\n void putVar32(int offset, u32 v) {\n _data[offset] = v | 0x80;\n _data[offset + 1] = (v >> 7) | 0x80;\n _data[offset + 2] = (v >> 14) | 0x80;\n _data[offset + 3] = (v >> 21) | 0x80;\n _data[offset + 4] = (v >> 28);\n }\n};\n\nclass RecordingBuffer : public Buffer {\n private:\n char _buf[RECORDING_BUFFER_SIZE - sizeof(Buffer)];\n\n public:\n RecordingBuffer() : Buffer() {\n }\n};\n\n\nclass Recording {\n private:\n static SpinLock _cpu_monitor_lock;\n static int _append_fd;\n\n static char* _agent_properties;\n static char* _jvm_args;\n static char* _jvm_flags;\n static char* _java_command;\n\n RecordingBuffer _buf[CONCURRENCY_LEVEL];\n int _fd;\n off_t _chunk_start;\n ThreadFilter _thread_set;\n Dictionary _packages;\n Dictionary _symbols;\n std::map _method_map;\n u64 _start_time;\n u64 _start_nanos;\n u64 _stop_time;\n u64 _stop_nanos;\n int _tid;\n int _available_processors;\n Buffer _cpu_monitor_buf;\n Timer* _cpu_monitor;\n CpuTimes _last_times;\n\n void startCpuMonitor(bool enabled) {\n _last_times.proc.real = OS::getProcessCpuTime(&_last_times.proc.user, &_last_times.proc.system);\n _last_times.total.real = OS::getTotalCpuTime(&_last_times.total.user, &_last_times.total.system);\n\n _cpu_monitor = enabled ? OS::startTimer(1000000000, cpuMonitorCallback, this) : NULL;\n _cpu_monitor_lock.unlock();\n }\n\n void stopCpuMonitor() {\n _cpu_monitor_lock.lock();\n if (_cpu_monitor != NULL) {\n OS::stopTimer(_cpu_monitor);\n }\n }\n\n void cpuMonitorCycle() {\n CpuTimes times;\n times.proc.real = OS::getProcessCpuTime(×.proc.user, ×.proc.system);\n times.total.real = OS::getTotalCpuTime(×.total.user, ×.total.system);\n\n float proc_user = 0, proc_system = 0, machine_total = 0;\n\n if (times.proc.real != (u64)-1 && times.proc.real > _last_times.proc.real) {\n float delta = (times.proc.real - _last_times.proc.real) * _available_processors;\n proc_user = ratio((times.proc.user - _last_times.proc.user) \/ delta);\n proc_system = ratio((times.proc.system - _last_times.proc.system) \/ delta);\n }\n\n if (times.total.real != (u64)-1 && times.total.real > _last_times.total.real) {\n float delta = times.total.real - _last_times.total.real;\n machine_total = ratio(((times.total.user + times.total.system) -\n (_last_times.total.user + _last_times.total.system)) \/ delta);\n if (machine_total < proc_user + proc_system) {\n machine_total = ratio(proc_user + proc_system);\n }\n }\n\n recordCpuLoad(&_cpu_monitor_buf, proc_user, proc_system, machine_total);\n flushIfNeeded(&_cpu_monitor_buf, BUFFER_LIMIT);\n\n _last_times = times;\n }\n\n static void cpuMonitorCallback(void* arg) {\n if (_cpu_monitor_lock.tryLock()) {\n ((Recording*)arg)->cpuMonitorCycle();\n _cpu_monitor_lock.unlock();\n }\n }\n\n static float ratio(float value) {\n return value < 0 ? 0 : value > 1 ? 1 : value;\n }\n\n public:\n Recording(int fd, Arguments& args) : _fd(fd), _thread_set(true), _packages(), _symbols(), _method_map() {\n _chunk_start = lseek(_fd, 0, SEEK_END);\n _start_time = OS::millis();\n _start_nanos = OS::nanotime();\n _tid = OS::threadId();\n addThread(_tid);\n VM::jvmti()->GetAvailableProcessors(&_available_processors);\n\n writeHeader(_buf);\n writeMetadata(_buf);\n writeRecordingInfo(_buf);\n writeSettings(_buf, args);\n if (!args.hasOption(NO_SYSTEM_INFO)) {\n writeOsCpuInfo(_buf);\n writeJvmInfo(_buf);\n }\n if (!args.hasOption(NO_SYSTEM_PROPS)) {\n writeSystemProperties(_buf);\n }\n flush(_buf);\n\n startCpuMonitor(!args.hasOption(NO_CPU_LOAD));\n }\n\n ~Recording() {\n stopCpuMonitor();\n\n _stop_nanos = OS::nanotime();\n _stop_time = OS::millis();\n\n for (int i = 0; i < CONCURRENCY_LEVEL; i++) {\n flush(&_buf[i]);\n }\n flush(&_cpu_monitor_buf);\n\n off_t cpool_offset = lseek(_fd, 0, SEEK_CUR);\n writeCpool(_buf);\n flush(_buf);\n\n off_t chunk_end = lseek(_fd, 0, SEEK_CUR);\n\n \/\/ Patch cpool size field\n _buf->putVar32(0, chunk_end - cpool_offset);\n ssize_t result = pwrite(_fd, _buf->data(), 5, cpool_offset);\n (void)result;\n\n \/\/ Patch chunk header\n _buf->put64(chunk_end - _chunk_start);\n _buf->put64(cpool_offset - _chunk_start);\n _buf->put64(68);\n _buf->put64(_start_time * 1000000);\n _buf->put64(_stop_nanos - _start_nanos);\n result = pwrite(_fd, _buf->data(), 40, _chunk_start + 8);\n (void)result;\n\n if (_append_fd >= 0) {\n OS::copyFile(_fd, _append_fd, 0, chunk_end);\n }\n\n close(_fd);\n }\n\n static void JNICALL appendRecording(JNIEnv* env, jclass cls, jstring file_name) {\n const char* file_name_str = env->GetStringUTFChars(file_name, NULL);\n if (file_name_str == NULL) {\n return;\n }\n\n _append_fd = open(file_name_str, O_WRONLY);\n if (_append_fd >= 0) {\n lseek(_append_fd, 0, SEEK_END);\n Profiler::_instance.stop();\n close(_append_fd);\n _append_fd = -1;\n } else {\n Log::warn(\"Failed to open JFR recording at %s: %s\", file_name_str, strerror(errno));\n }\n\n env->ReleaseStringUTFChars(file_name, file_name_str);\n }\n\n Buffer* buffer(int lock_index) {\n return &_buf[lock_index];\n }\n\n void fillNativeMethodInfo(MethodInfo* mi, const char* name) {\n mi->_class = Profiler::_instance.classMap()->lookup(\"\");\n mi->_modifiers = 0x100;\n mi->_line_number_table_size = 0;\n mi->_line_number_table = NULL;\n\n if (name[0] == '_' && name[1] == 'Z') {\n int status;\n char* demangled = abi::__cxa_demangle(name, NULL, NULL, &status);\n if (demangled != NULL) {\n char* p = strchr(demangled, '(');\n if (p != NULL) *p = 0;\n mi->_name = _symbols.lookup(demangled);\n mi->_sig = _symbols.lookup(\"()L;\");\n mi->_type = FRAME_CPP;\n free(demangled);\n return;\n }\n }\n\n size_t len = strlen(name);\n if (len >= 4 && strcmp(name + len - 4, \"_[k]\") == 0) {\n mi->_name = _symbols.lookup(name, len - 4);\n mi->_sig = _symbols.lookup(\"(Lk;)L;\");\n mi->_type = FRAME_KERNEL;\n } else {\n mi->_name = _symbols.lookup(name);\n mi->_sig = _symbols.lookup(\"()L;\");\n mi->_type = FRAME_NATIVE;\n }\n }\n\n void fillJavaMethodInfo(MethodInfo* mi, jmethodID method) {\n jvmtiEnv* jvmti = VM::jvmti();\n jclass method_class;\n char* class_name = NULL;\n char* method_name = NULL;\n char* method_sig = NULL;\n\n if (jvmti->GetMethodDeclaringClass(method, &method_class) == 0 &&\n jvmti->GetClassSignature(method_class, &class_name, NULL) == 0 &&\n jvmti->GetMethodName(method, &method_name, &method_sig, NULL) == 0) {\n mi->_class = Profiler::_instance.classMap()->lookup(class_name + 1, strlen(class_name) - 2);\n mi->_name = _symbols.lookup(method_name);\n mi->_sig = _symbols.lookup(method_sig);\n } else {\n mi->_class = Profiler::_instance.classMap()->lookup(\"\");\n mi->_name = _symbols.lookup(\"jvmtiError\");\n mi->_sig = _symbols.lookup(\"()L;\");\n }\n\n jvmti->Deallocate((unsigned char*)method_sig);\n jvmti->Deallocate((unsigned char*)method_name);\n jvmti->Deallocate((unsigned char*)class_name);\n\n if (jvmti->GetMethodModifiers(method, &mi->_modifiers) != 0) {\n mi->_modifiers = 0;\n }\n\n if (jvmti->GetLineNumberTable(method, &mi->_line_number_table_size, &mi->_line_number_table) != 0) {\n mi->_line_number_table_size = 0;\n mi->_line_number_table = NULL;\n }\n\n mi->_type = FRAME_INTERPRETED;\n }\n\n MethodInfo* resolveMethod(ASGCT_CallFrame& frame) {\n jmethodID method = frame.method_id;\n MethodInfo* mi = &_method_map[method];\n\n if (mi->_key == 0) {\n mi->_key = _method_map.size();\n\n if (method == NULL) {\n fillNativeMethodInfo(mi, \"unknown\");\n } else if (frame.bci == BCI_NATIVE_FRAME || frame.bci == BCI_ERROR) {\n fillNativeMethodInfo(mi, (const char*)method);\n } else {\n fillJavaMethodInfo(mi, method);\n }\n }\n\n return mi;\n }\n\n u32 getPackage(const char* class_name) {\n const char* package = strrchr(class_name, '\/');\n if (package == NULL) {\n return 0;\n }\n if (class_name[0] == '[') {\n class_name = strchr(class_name, 'L') + 1;\n }\n return _packages.lookup(class_name, package - class_name);\n }\n\n bool parseAgentProperties() {\n JNIEnv* env = VM::jni();\n jclass vm_support = env->FindClass(\"jdk\/internal\/vm\/VMSupport\");\n if (vm_support == NULL) vm_support = env->FindClass(\"sun\/misc\/VMSupport\");\n if (vm_support != NULL) {\n jmethodID get_agent_props = env->GetStaticMethodID(vm_support, \"getAgentProperties\", \"()Ljava\/util\/Properties;\");\n jmethodID to_string = env->GetMethodID(env->FindClass(\"java\/lang\/Object\"), \"toString\", \"()Ljava\/lang\/String;\");\n if (get_agent_props != NULL && to_string != NULL) {\n jobject props = env->CallStaticObjectMethod(vm_support, get_agent_props);\n if (props != NULL) {\n jstring str = (jstring)env->CallObjectMethod(props, to_string);\n if (str != NULL) {\n _agent_properties = (char*)env->GetStringUTFChars(str, NULL);\n }\n }\n }\n }\n env->ExceptionClear();\n\n if (_agent_properties == NULL) {\n return false;\n }\n\n char* p = _agent_properties + 1;\n p[strlen(p) - 1] = 0;\n\n while (*p) {\n if (strncmp(p, \"sun.jvm.args=\", 13) == 0) {\n _jvm_args = p + 13;\n } else if (strncmp(p, \"sun.jvm.flags=\", 14) == 0) {\n _jvm_flags = p + 14;\n } else if (strncmp(p, \"sun.java.command=\", 17) == 0) {\n _java_command = p + 17;\n }\n\n if ((p = strstr(p, \", \")) == NULL) {\n break;\n }\n\n *p = 0;\n p += 2;\n }\n\n return true;\n }\n\n void flush(Buffer* buf) {\n ssize_t result = write(_fd, buf->data(), buf->offset());\n (void)result;\n buf->reset();\n }\n\n void flushIfNeeded(Buffer* buf, int limit = RECORDING_BUFFER_LIMIT) {\n if (buf->offset() >= limit) {\n flush(buf);\n }\n }\n\n void writeHeader(Buffer* buf) {\n buf->put(\"FLR\\0\", 4); \/\/ magic\n buf->put16(2); \/\/ major\n buf->put16(0); \/\/ minor\n buf->put64(0); \/\/ chunk size\n buf->put64(0); \/\/ cpool offset\n buf->put64(0); \/\/ meta offset\n buf->put64(_start_time * 1000000); \/\/ start time, ns\n buf->put64(0); \/\/ duration, ns\n buf->put64(_start_nanos); \/\/ start ticks\n buf->put64(1000000000); \/\/ ticks per sec\n buf->put32(1); \/\/ features\n }\n\n void writeMetadata(Buffer* buf) {\n int metadata_start = buf->skip(5); \/\/ size will be patched later\n buf->putVar32(T_METADATA);\n buf->putVar64(_start_nanos);\n buf->putVar32(0);\n buf->putVar32(1);\n\n std::vector& strings = JfrMetadata::strings();\n buf->putVar32(strings.size());\n for (int i = 0; i < strings.size(); i++) {\n buf->putUtf8(strings[i].c_str());\n }\n\n writeElement(buf, JfrMetadata::root());\n\n buf->putVar32(metadata_start, buf->offset() - metadata_start);\n }\n\n void writeElement(Buffer* buf, const Element* e) {\n buf->putVar32(e->_name);\n\n buf->putVar32(e->_attributes.size());\n for (int i = 0; i < e->_attributes.size(); i++) {\n buf->putVar32(e->_attributes[i]._key);\n buf->putVar32(e->_attributes[i]._value);\n }\n\n buf->putVar32(e->_children.size());\n for (int i = 0; i < e->_children.size(); i++) {\n writeElement(buf, e->_children[i]);\n }\n }\n\n void writeRecordingInfo(Buffer* buf) {\n int start = buf->skip(1);\n buf->put8(T_ACTIVE_RECORDING);\n buf->putVar64(_start_nanos);\n buf->putVar32(0);\n buf->putVar32(_tid);\n buf->putVar32(1);\n buf->putUtf8(\"async-profiler \" PROFILER_VERSION);\n buf->putUtf8(\"async-profiler.jfr\");\n buf->putVar64(0x7fffffffffffffffULL);\n buf->putVar32(0);\n buf->putVar64(_start_time);\n buf->putVar64(0x7fffffffffffffffULL);\n buf->put8(start, buf->offset() - start);\n }\n\n void writeSettings(Buffer* buf, Arguments& args) {\n writeStringSetting(buf, T_ACTIVE_RECORDING, \"version\", PROFILER_VERSION);\n writeStringSetting(buf, T_ACTIVE_RECORDING, \"ring\", SETTING_RING[args._ring]);\n writeStringSetting(buf, T_ACTIVE_RECORDING, \"cstack\", SETTING_CSTACK[args._cstack]);\n writeStringSetting(buf, T_ACTIVE_RECORDING, \"event\", args._event);\n writeStringSetting(buf, T_ACTIVE_RECORDING, \"filter\", args._filter);\n writeStringSetting(buf, T_ACTIVE_RECORDING, \"begin\", args._begin);\n writeStringSetting(buf, T_ACTIVE_RECORDING, \"end\", args._end);\n writeListSetting(buf, T_ACTIVE_RECORDING, \"include\", args._buf, args._include);\n writeListSetting(buf, T_ACTIVE_RECORDING, \"exclude\", args._buf, args._exclude);\n writeIntSetting(buf, T_ACTIVE_RECORDING, \"jstackdepth\", args._jstackdepth);\n writeIntSetting(buf, T_ACTIVE_RECORDING, \"safemode\", args._safe_mode);\n writeIntSetting(buf, T_ACTIVE_RECORDING, \"jfropts\", args._jfr_options);\n\n writeBoolSetting(buf, T_EXECUTION_SAMPLE, \"enabled\", args._event != NULL);\n if (args._event != NULL) {\n writeIntSetting(buf, T_EXECUTION_SAMPLE, \"interval\", args._interval);\n }\n\n writeBoolSetting(buf, T_ALLOC_IN_NEW_TLAB, \"enabled\", args._alloc > 0);\n writeBoolSetting(buf, T_ALLOC_OUTSIDE_TLAB, \"enabled\", args._alloc > 0);\n if (args._alloc > 0) {\n writeIntSetting(buf, T_ALLOC_IN_NEW_TLAB, \"alloc\", args._alloc);\n }\n\n writeBoolSetting(buf, T_MONITOR_ENTER, \"enabled\", args._lock > 0);\n writeBoolSetting(buf, T_THREAD_PARK, \"enabled\", args._lock > 0);\n if (args._lock > 0) {\n writeIntSetting(buf, T_MONITOR_ENTER, \"lock\", args._lock);\n }\n }\n\n void writeStringSetting(Buffer* buf, int category, const char* key, const char* value) {\n int start = buf->skip(5);\n buf->put8(T_ACTIVE_SETTING);\n buf->putVar64(_start_nanos);\n buf->putVar32(0);\n buf->putVar32(_tid);\n buf->putVar32(category);\n buf->putUtf8(key);\n buf->putUtf8(value);\n buf->putVar32(start, buf->offset() - start);\n flushIfNeeded(buf);\n }\n\n void writeBoolSetting(Buffer* buf, int category, const char* key, bool value) {\n writeStringSetting(buf, category, key, value ? \"true\" : \"false\");\n }\n\n void writeIntSetting(Buffer* buf, int category, const char* key, long value) {\n char str[32];\n sprintf(str, \"%ld\", value);\n writeStringSetting(buf, category, key, str);\n }\n\n void writeListSetting(Buffer* buf, int category, const char* key, const char* base, int offset) {\n while (offset != 0) {\n writeStringSetting(buf, category, key, base + offset);\n offset = ((int*)(base + offset))[-1];\n }\n }\n\n void writeOsCpuInfo(Buffer* buf) {\n struct utsname u;\n if (uname(&u) != 0) {\n return;\n }\n\n char str[512];\n snprintf(str, sizeof(str) - 1, \"uname: %s %s %s %s\", u.sysname, u.release, u.version, u.machine);\n str[sizeof(str) - 1] = 0;\n\n int start = buf->skip(5);\n buf->put8(T_OS_INFORMATION);\n buf->putVar64(_start_nanos);\n buf->putUtf8(str);\n buf->putVar32(start, buf->offset() - start);\n\n start = buf->skip(5);\n buf->put8(T_CPU_INFORMATION);\n buf->putVar64(_start_nanos);\n buf->putUtf8(u.machine);\n buf->putUtf8(OS::getCpuDescription(str, sizeof(str) - 1) ? str : \"\");\n buf->putVar32(1);\n buf->putVar32(_available_processors);\n buf->putVar32(_available_processors);\n buf->putVar32(start, buf->offset() - start);\n }\n\n void writeJvmInfo(Buffer* buf) {\n if (_agent_properties == NULL && !parseAgentProperties()) {\n return;\n }\n\n char* jvm_name = NULL;\n char* jvm_version = NULL;\n\n jvmtiEnv* jvmti = VM::jvmti();\n jvmti->GetSystemProperty(\"java.vm.name\", &jvm_name);\n jvmti->GetSystemProperty(\"java.vm.version\", &jvm_version);\n\n flushIfNeeded(buf, RECORDING_BUFFER_LIMIT - 5 * MAX_STRING_LENGTH);\n int start = buf->skip(5);\n buf->put8(T_JVM_INFORMATION);\n buf->putVar64(_start_nanos);\n buf->putUtf8(jvm_name);\n buf->putUtf8(jvm_version);\n buf->putUtf8(_jvm_args);\n buf->putUtf8(_jvm_flags);\n buf->putUtf8(_java_command);\n buf->putVar64(OS::processStartTime());\n buf->putVar32(OS::processId());\n buf->putVar32(start, buf->offset() - start);\n\n jvmti->Deallocate((unsigned char*)jvm_version);\n jvmti->Deallocate((unsigned char*)jvm_name);\n }\n\n void writeSystemProperties(Buffer* buf) {\n jvmtiEnv* jvmti = VM::jvmti();\n jint count;\n char** keys;\n if (jvmti->GetSystemProperties(&count, &keys) != 0) {\n return;\n }\n\n for (int i = 0; i < count; i++) {\n char* key = keys[i];\n char* value = NULL;\n if (jvmti->GetSystemProperty(key, &value) == 0) {\n flushIfNeeded(buf, RECORDING_BUFFER_LIMIT - 2 * MAX_STRING_LENGTH);\n int start = buf->skip(5);\n buf->put8(T_INITIAL_SYSTEM_PROPERTY);\n buf->putVar64(_start_nanos);\n buf->putUtf8(key);\n buf->putUtf8(value);\n buf->putVar32(start, buf->offset() - start);\n jvmti->Deallocate((unsigned char*)value);\n }\n }\n\n jvmti->Deallocate((unsigned char*)keys);\n }\n\n void writeCpool(Buffer* buf) {\n buf->skip(5); \/\/ size will be patched later\n buf->putVar32(T_CPOOL);\n buf->putVar64(_start_nanos);\n buf->putVar32(0);\n buf->putVar32(0);\n buf->putVar32(1);\n\n buf->putVar32(8);\n\n writeFrameTypes(buf);\n writeThreadStates(buf);\n writeThreads(buf);\n writeStackTraces(buf);\n writeMethods(buf);\n writeClasses(buf);\n writePackages(buf);\n writeSymbols(buf);\n }\n\n void writeFrameTypes(Buffer* buf) {\n buf->putVar32(T_FRAME_TYPE);\n buf->putVar32(6);\n buf->putVar32(FRAME_INTERPRETED); buf->putUtf8(\"Interpreted\");\n buf->putVar32(FRAME_JIT_COMPILED); buf->putUtf8(\"JIT compiled\");\n buf->putVar32(FRAME_INLINED); buf->putUtf8(\"Inlined\");\n buf->putVar32(FRAME_NATIVE); buf->putUtf8(\"Native\");\n buf->putVar32(FRAME_CPP); buf->putUtf8(\"C++\");\n buf->putVar32(FRAME_KERNEL); buf->putUtf8(\"Kernel\");\n }\n\n void writeThreadStates(Buffer* buf) {\n buf->putVar32(T_THREAD_STATE);\n buf->putVar32(2);\n buf->putVar32(THREAD_RUNNING); buf->putUtf8(\"STATE_RUNNABLE\");\n buf->putVar32(THREAD_SLEEPING); buf->putUtf8(\"STATE_SLEEPING\");\n }\n\n void writeThreads(Buffer* buf) {\n std::vector threads;\n _thread_set.collect(threads);\n\n MutexLocker ml(Profiler::_instance._thread_names_lock);\n std::map& thread_names = Profiler::_instance._thread_names;\n std::map& thread_ids = Profiler::_instance._thread_ids;\n char name_buf[32];\n\n buf->putVar32(T_THREAD);\n buf->putVar32(threads.size());\n for (int i = 0; i < threads.size(); i++) {\n const char* thread_name;\n jlong thread_id;\n std::map::const_iterator it = thread_names.find(threads[i]);\n if (it != thread_names.end()) {\n thread_name = it->second.c_str();\n thread_id = thread_ids[threads[i]];\n } else {\n sprintf(name_buf, \"[tid=%d]\", threads[i]);\n thread_name = name_buf;\n thread_id = 0;\n }\n\n buf->putVar32(threads[i]);\n buf->putUtf8(thread_name);\n buf->putVar32(threads[i]);\n if (thread_id == 0) {\n buf->put8(0);\n } else {\n buf->putUtf8(thread_name);\n }\n buf->putVar64(thread_id);\n flushIfNeeded(buf);\n }\n }\n\n void writeStackTraces(Buffer* buf) {\n std::map traces;\n Profiler::_instance._call_trace_storage.collectTraces(traces);\n\n buf->putVar32(T_STACK_TRACE);\n buf->putVar32(traces.size());\n for (std::map::const_iterator it = traces.begin(); it != traces.end(); ++it) {\n CallTrace* trace = it->second;\n buf->putVar32(it->first);\n buf->putVar32(0); \/\/ truncated\n buf->putVar32(trace->num_frames);\n for (int i = 0; i < trace->num_frames; i++) {\n MethodInfo* mi = resolveMethod(trace->frames[i]);\n buf->putVar32(mi->_key);\n jint bci = trace->frames[i].bci;\n if (bci >= 0) {\n buf->putVar32(mi->getLineNumber(bci));\n buf->putVar32(bci);\n } else {\n buf->put8(0);\n buf->put8(0);\n }\n buf->putVar32(mi->_type);\n flushIfNeeded(buf);\n }\n flushIfNeeded(buf);\n }\n }\n\n void writeMethods(Buffer* buf) {\n jvmtiEnv* jvmti = VM::jvmti();\n\n buf->putVar32(T_METHOD);\n buf->putVar32(_method_map.size());\n for (std::map::const_iterator it = _method_map.begin(); it != _method_map.end(); ++it) {\n const MethodInfo& mi = it->second;\n buf->putVar32(mi._key);\n buf->putVar32(mi._class);\n buf->putVar32(mi._name);\n buf->putVar32(mi._sig);\n buf->putVar32(mi._modifiers);\n buf->putVar32(0); \/\/ hidden\n flushIfNeeded(buf);\n\n if (mi._line_number_table != NULL) {\n jvmti->Deallocate((unsigned char*)mi._line_number_table);\n }\n }\n }\n\n void writeClasses(Buffer* buf) {\n std::map classes;\n Profiler::_instance.classMap()->collect(classes);\n\n buf->putVar32(T_CLASS);\n buf->putVar32(classes.size());\n for (std::map::const_iterator it = classes.begin(); it != classes.end(); ++it) {\n const char* name = it->second;\n buf->putVar32(it->first);\n buf->putVar32(0); \/\/ classLoader\n buf->putVar32(_symbols.lookup(name));\n buf->putVar32(getPackage(name));\n buf->putVar32(0); \/\/ access flags\n flushIfNeeded(buf);\n }\n }\n\n void writePackages(Buffer* buf) {\n std::map packages;\n _packages.collect(packages);\n\n buf->putVar32(T_PACKAGE);\n buf->putVar32(packages.size());\n for (std::map::const_iterator it = packages.begin(); it != packages.end(); ++it) {\n buf->putVar32(it->first);\n buf->putVar32(_symbols.lookup(it->second));\n flushIfNeeded(buf);\n }\n }\n\n void writeSymbols(Buffer* buf) {\n std::map symbols;\n _symbols.collect(symbols);\n\n buf->putVar32(T_SYMBOL);\n buf->putVar32(symbols.size());\n for (std::map::const_iterator it = symbols.begin(); it != symbols.end(); ++it) {\n buf->putVar32(it->first);\n buf->putUtf8(it->second);\n flushIfNeeded(buf);\n }\n }\n\n void recordExecutionSample(Buffer* buf, int tid, u32 call_trace_id, ExecutionEvent* event) {\n int start = buf->skip(1);\n buf->put8(T_EXECUTION_SAMPLE);\n buf->putVar64(OS::nanotime());\n buf->putVar32(tid);\n buf->putVar32(call_trace_id);\n buf->putVar32(event->_thread_state);\n buf->put8(start, buf->offset() - start);\n }\n\n void recordAllocationInNewTLAB(Buffer* buf, int tid, u32 call_trace_id, AllocEvent* event) {\n int start = buf->skip(1);\n buf->put8(T_ALLOC_IN_NEW_TLAB);\n buf->putVar64(OS::nanotime());\n buf->putVar32(tid);\n buf->putVar32(call_trace_id);\n buf->putVar32(event->_class_id);\n buf->putVar64(event->_instance_size);\n buf->putVar64(event->_total_size);\n buf->put8(start, buf->offset() - start);\n }\n\n void recordAllocationOutsideTLAB(Buffer* buf, int tid, u32 call_trace_id, AllocEvent* event) {\n int start = buf->skip(1);\n buf->put8(T_ALLOC_OUTSIDE_TLAB);\n buf->putVar64(OS::nanotime());\n buf->putVar32(tid);\n buf->putVar32(call_trace_id);\n buf->putVar32(event->_class_id);\n buf->putVar64(event->_total_size);\n buf->put8(start, buf->offset() - start);\n }\n\n void recordMonitorBlocked(Buffer* buf, int tid, u32 call_trace_id, LockEvent* event) {\n int start = buf->skip(1);\n buf->put8(T_MONITOR_ENTER);\n buf->putVar64(event->_start_time);\n buf->putVar64(event->_end_time - event->_start_time);\n buf->putVar32(tid);\n buf->putVar32(call_trace_id);\n buf->putVar32(event->_class_id);\n buf->putVar64(event->_address);\n buf->put8(start, buf->offset() - start);\n }\n\n void recordThreadPark(Buffer* buf, int tid, u32 call_trace_id, LockEvent* event) {\n int start = buf->skip(1);\n buf->put8(T_THREAD_PARK);\n buf->putVar64(event->_start_time);\n buf->putVar64(event->_end_time - event->_start_time);\n buf->putVar32(tid);\n buf->putVar32(call_trace_id);\n buf->putVar32(event->_class_id);\n buf->putVar64(event->_timeout);\n buf->putVar64(event->_address);\n buf->put8(start, buf->offset() - start);\n }\n\n void recordCpuLoad(Buffer* buf, float proc_user, float proc_system, float machine_total) {\n int start = buf->skip(1);\n buf->put8(T_CPU_LOAD);\n buf->putVar64(OS::nanotime());\n buf->putFloat(proc_user);\n buf->putFloat(proc_system);\n buf->putFloat(machine_total);\n buf->put8(start, buf->offset() - start);\n }\n\n void addThread(int tid) {\n if (!_thread_set.accept(tid)) {\n _thread_set.add(tid);\n }\n }\n};\n\nSpinLock Recording::_cpu_monitor_lock(1);\nint Recording::_append_fd = -1;\n\nchar* Recording::_agent_properties = NULL;\nchar* Recording::_jvm_args = NULL;\nchar* Recording::_jvm_flags = NULL;\nchar* Recording::_java_command = NULL;\n\n\nError FlightRecorder::start(Arguments& args, bool reset) {\n if (args._file == NULL || args._file[0] == 0) {\n return Error(\"Flight Recorder output file is not specified\");\n }\n\n if (args.hasOption(JFR_SYNC) && !loadJavaHelper()) {\n return Error(\"Could not load JFR combiner class\");\n }\n\n int fd = open(args._file, O_CREAT | O_RDWR | (reset ? O_TRUNC : 0), 0644);\n if (fd == -1) {\n return Error(\"Could not open Flight Recorder output file\");\n }\n\n if (args.hasOption(JFR_TEMP_FILE)) {\n unlink(args._file);\n }\n\n _rec = new Recording(fd, args);\n return Error::OK;\n}\n\nvoid FlightRecorder::stop() {\n if (_rec != NULL) {\n delete _rec;\n _rec = NULL;\n }\n}\n\nbool FlightRecorder::loadJavaHelper() {\n if (!_java_helper_loaded) {\n JNIEnv* jni = VM::jni();\n const JNINativeMethod native_method = {\n (char*)\"appendRecording\", (char*)\"(Ljava\/lang\/String;)V\",\n (void*)Recording::appendRecording\n };\n\n jclass cls = jni->DefineClass(NULL, NULL, (const jbyte*)JFR_COMBINER_CLASS, sizeof(JFR_COMBINER_CLASS));\n if (cls == NULL || jni->RegisterNatives(cls, &native_method, 1) != 0 || jni->GetMethodID(cls, \"\", \"()V\") == NULL) {\n jni->ExceptionClear();\n return false;\n }\n\n _java_helper_loaded = true;\n }\n\n return true;\n}\n\nvoid FlightRecorder::recordEvent(int lock_index, int tid, u32 call_trace_id,\n int event_type, Event* event, u64 counter) {\n if (_rec != NULL) {\n Buffer* buf = _rec->buffer(lock_index);\n switch (event_type) {\n case 0:\n _rec->recordExecutionSample(buf, tid, call_trace_id, (ExecutionEvent*)event);\n break;\n case BCI_ALLOC:\n _rec->recordAllocationInNewTLAB(buf, tid, call_trace_id, (AllocEvent*)event);\n break;\n case BCI_ALLOC_OUTSIDE_TLAB:\n _rec->recordAllocationOutsideTLAB(buf, tid, call_trace_id, (AllocEvent*)event);\n break;\n case BCI_LOCK:\n _rec->recordMonitorBlocked(buf, tid, call_trace_id, (LockEvent*)event);\n break;\n case BCI_PARK:\n _rec->recordThreadPark(buf, tid, call_trace_id, (LockEvent*)event);\n break;\n }\n _rec->flushIfNeeded(buf);\n _rec->addThread(tid);\n }\n}\n","avg_line_length":32.1840888067,"max_line_length":129,"alphanum_fraction":0.5621281366} {"size":10666,"ext":"cc","lang":"C++","max_stars_count":27.0,"content":"\/*\n * libjingle\n * Copyright 2015 Google Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#include \"talk\/app\/webrtc\/java\/jni\/jni_helpers.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace webrtc_jni {\n\nstatic JavaVM* g_jvm = nullptr;\n\nstatic pthread_once_t g_jni_ptr_once = PTHREAD_ONCE_INIT;\n\n\/\/ Key for per-thread JNIEnv* data. Non-NULL in threads attached to |g_jvm| by\n\/\/ AttachCurrentThreadIfNeeded(), NULL in unattached threads and threads that\n\/\/ were attached by the JVM because of a Java->native call.\nstatic pthread_key_t g_jni_ptr;\n\nJavaVM *GetJVM() {\n RTC_CHECK(g_jvm) << \"JNI_OnLoad failed to run?\";\n return g_jvm;\n}\n\n\/\/ Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.\nJNIEnv* GetEnv() {\n void* env = NULL;\n jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);\n RTC_CHECK(((env != NULL) && (status == JNI_OK)) ||\n ((env == NULL) && (status == JNI_EDETACHED)))\n << \"Unexpected GetEnv return: \" << status << \":\" << env;\n return reinterpret_cast(env);\n}\n\nstatic void ThreadDestructor(void* prev_jni_ptr) {\n \/\/ This function only runs on threads where |g_jni_ptr| is non-NULL, meaning\n \/\/ we were responsible for originally attaching the thread, so are responsible\n \/\/ for detaching it now. However, because some JVM implementations (notably\n \/\/ Oracle's http:\/\/goo.gl\/eHApYT) also use the pthread_key_create mechanism,\n \/\/ the JVMs accounting info for this thread may already be wiped out by the\n \/\/ time this is called. Thus it may appear we are already detached even though\n \/\/ it was our responsibility to detach! Oh well.\n if (!GetEnv())\n return;\n\n RTC_CHECK(GetEnv() == prev_jni_ptr)\n << \"Detaching from another thread: \" << prev_jni_ptr << \":\" << GetEnv();\n jint status = g_jvm->DetachCurrentThread();\n RTC_CHECK(status == JNI_OK) << \"Failed to detach thread: \" << status;\n RTC_CHECK(!GetEnv()) << \"Detaching was a successful no-op???\";\n}\n\nstatic void CreateJNIPtrKey() {\n RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))\n << \"pthread_key_create\";\n}\n\njint InitGlobalJniVariables(JavaVM *jvm) {\n RTC_CHECK(!g_jvm) << \"InitGlobalJniVariables!\";\n g_jvm = jvm;\n RTC_CHECK(g_jvm) << \"InitGlobalJniVariables handed NULL?\";\n\n RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << \"pthread_once\";\n\n JNIEnv* jni = nullptr;\n if (jvm->GetEnv(reinterpret_cast(&jni), JNI_VERSION_1_6) != JNI_OK)\n return -1;\n\n return JNI_VERSION_1_6;\n}\n\n\/\/ Return thread ID as a string.\nstatic std::string GetThreadId() {\n char buf[21]; \/\/ Big enough to hold a kuint64max plus terminating NULL.\n RTC_CHECK_LT(snprintf(buf, sizeof(buf), \"%ld\",\n static_cast(syscall(__NR_gettid))),\n sizeof(buf))\n << \"Thread id is bigger than uint64??\";\n return std::string(buf);\n}\n\n\/\/ Return the current thread's name.\nstatic std::string GetThreadName() {\n char name[17] = {0};\n if (prctl(PR_GET_NAME, name) != 0)\n return std::string(\"\");\n return std::string(name);\n}\n\n\/\/ Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary.\nJNIEnv* AttachCurrentThreadIfNeeded() {\n JNIEnv* jni = GetEnv();\n if (jni)\n return jni;\n RTC_CHECK(!pthread_getspecific(g_jni_ptr))\n << \"TLS has a JNIEnv* but not attached?\";\n\n std::string name(GetThreadName() + \" - \" + GetThreadId());\n JavaVMAttachArgs args;\n args.version = JNI_VERSION_1_6;\n args.name = &name[0];\n args.group = NULL;\n \/\/ Deal with difference in signatures between Oracle's jni.h and Android's.\n#ifdef _JAVASOFT_JNI_H_ \/\/ Oracle's jni.h violates the JNI spec!\n void* env = NULL;\n#else\n JNIEnv* env = NULL;\n#endif\n RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args))\n << \"Failed to attach thread\";\n RTC_CHECK(env) << \"AttachCurrentThread handed back NULL!\";\n jni = reinterpret_cast(env);\n RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << \"pthread_setspecific\";\n return jni;\n}\n\n\/\/ Return a |jlong| that will correctly convert back to |ptr|. This is needed\n\/\/ because the alternative (of silently passing a 32-bit pointer to a vararg\n\/\/ function expecting a 64-bit param) picks up garbage in the high 32 bits.\njlong jlongFromPointer(void* ptr) {\n static_assert(sizeof(intptr_t) <= sizeof(jlong),\n \"Time to rethink the use of jlongs\");\n \/\/ Going through intptr_t to be obvious about the definedness of the\n \/\/ conversion from pointer to integral type. intptr_t to jlong is a standard\n \/\/ widening by the static_assert above.\n jlong ret = reinterpret_cast(ptr);\n RTC_DCHECK(reinterpret_cast(ret) == ptr);\n return ret;\n}\n\n\/\/ JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and\n\/\/ found object\/class\/method\/field is non-null.\njmethodID GetMethodID(\n JNIEnv* jni, jclass c, const std::string& name, const char* signature) {\n jmethodID m = jni->GetMethodID(c, name.c_str(), signature);\n CHECK_EXCEPTION(jni) << \"error during GetMethodID: \" << name << \", \"\n << signature;\n RTC_CHECK(m) << name << \", \" << signature;\n return m;\n}\n\njmethodID GetStaticMethodID(\n JNIEnv* jni, jclass c, const char* name, const char* signature) {\n jmethodID m = jni->GetStaticMethodID(c, name, signature);\n CHECK_EXCEPTION(jni) << \"error during GetStaticMethodID: \" << name << \", \"\n << signature;\n RTC_CHECK(m) << name << \", \" << signature;\n return m;\n}\n\njfieldID GetFieldID(\n JNIEnv* jni, jclass c, const char* name, const char* signature) {\n jfieldID f = jni->GetFieldID(c, name, signature);\n CHECK_EXCEPTION(jni) << \"error during GetFieldID\";\n RTC_CHECK(f) << name << \", \" << signature;\n return f;\n}\n\njclass GetObjectClass(JNIEnv* jni, jobject object) {\n jclass c = jni->GetObjectClass(object);\n CHECK_EXCEPTION(jni) << \"error during GetObjectClass\";\n RTC_CHECK(c) << \"GetObjectClass returned NULL\";\n return c;\n}\n\njobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {\n jobject o = jni->GetObjectField(object, id);\n CHECK_EXCEPTION(jni) << \"error during GetObjectField\";\n RTC_CHECK(o) << \"GetObjectField returned NULL\";\n return o;\n}\n\njstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {\n return static_cast(GetObjectField(jni, object, id));\n}\n\njlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {\n jlong l = jni->GetLongField(object, id);\n CHECK_EXCEPTION(jni) << \"error during GetLongField\";\n return l;\n}\n\njint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {\n jint i = jni->GetIntField(object, id);\n CHECK_EXCEPTION(jni) << \"error during GetIntField\";\n return i;\n}\n\nbool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {\n jboolean b = jni->GetBooleanField(object, id);\n CHECK_EXCEPTION(jni) << \"error during GetBooleanField\";\n return b;\n}\n\n\/\/ Java references to \"null\" can only be distinguished as such in C++ by\n\/\/ creating a local reference, so this helper wraps that logic.\nbool IsNull(JNIEnv* jni, jobject obj) {\n ScopedLocalRefFrame local_ref_frame(jni);\n return jni->NewLocalRef(obj) == NULL;\n}\n\n\/\/ Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.\njstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {\n jstring jstr = jni->NewStringUTF(native.c_str());\n CHECK_EXCEPTION(jni) << \"error during NewStringUTF\";\n return jstr;\n}\n\n\/\/ Given a (UTF-16) jstring return a new UTF-8 native string.\nstd::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {\n const char* chars = jni->GetStringUTFChars(j_string, NULL);\n CHECK_EXCEPTION(jni) << \"Error during GetStringUTFChars\";\n std::string str(chars, jni->GetStringUTFLength(j_string));\n CHECK_EXCEPTION(jni) << \"Error during GetStringUTFLength\";\n jni->ReleaseStringUTFChars(j_string, chars);\n CHECK_EXCEPTION(jni) << \"Error during ReleaseStringUTFChars\";\n return str;\n}\n\n\/\/ Return the (singleton) Java Enum object corresponding to |index|;\njobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,\n const std::string& state_class_name, int index) {\n jmethodID state_values_id = GetStaticMethodID(\n jni, state_class, \"values\", (\"()[L\" + state_class_name + \";\").c_str());\n jobjectArray state_values = static_cast(\n jni->CallStaticObjectMethod(state_class, state_values_id));\n CHECK_EXCEPTION(jni) << \"error during CallStaticObjectMethod\";\n jobject ret = jni->GetObjectArrayElement(state_values, index);\n CHECK_EXCEPTION(jni) << \"error during GetObjectArrayElement\";\n return ret;\n}\n\njobject NewGlobalRef(JNIEnv* jni, jobject o) {\n jobject ret = jni->NewGlobalRef(o);\n CHECK_EXCEPTION(jni) << \"error during NewGlobalRef\";\n RTC_CHECK(ret);\n return ret;\n}\n\nvoid DeleteGlobalRef(JNIEnv* jni, jobject o) {\n jni->DeleteGlobalRef(o);\n CHECK_EXCEPTION(jni) << \"error during DeleteGlobalRef\";\n}\n\n\/\/ Scope Java local references to the lifetime of this object. Use in all C++\n\/\/ callbacks (i.e. entry points that don't originate in a Java callstack\n\/\/ through a \"native\" method call).\nScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {\n RTC_CHECK(!jni_->PushLocalFrame(0)) << \"Failed to PushLocalFrame\";\n}\nScopedLocalRefFrame::~ScopedLocalRefFrame() {\n jni_->PopLocalFrame(NULL);\n}\n\n} \/\/ namespace webrtc_jni\n","avg_line_length":37.8226950355,"max_line_length":80,"alphanum_fraction":0.711888243} {"size":7505,"ext":"cc","lang":"C++","max_stars_count":8.0,"content":"\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/test\/fake_encoder.h\"\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#include \"webrtc\/modules\/video_coding\/codecs\/interface\/video_codec_interface.h\"\n#include \"webrtc\/system_wrappers\/interface\/sleep.h\"\n\nnamespace webrtc {\nnamespace test {\n\nFakeEncoder::FakeEncoder(Clock* clock)\n : clock_(clock),\n callback_(NULL),\n target_bitrate_kbps_(0),\n max_target_bitrate_kbps_(-1),\n last_encode_time_ms_(0) {\n \/\/ Generate some arbitrary not-all-zero data\n for (size_t i = 0; i < sizeof(encoded_buffer_); ++i) {\n encoded_buffer_[i] = static_cast(i);\n }\n}\n\nFakeEncoder::~FakeEncoder() {}\n\nvoid FakeEncoder::SetMaxBitrate(int max_kbps) {\n assert(max_kbps >= -1); \/\/ max_kbps == -1 disables it.\n max_target_bitrate_kbps_ = max_kbps;\n}\n\nint32_t FakeEncoder::InitEncode(const VideoCodec* config,\n int32_t number_of_cores,\n size_t max_payload_size) {\n config_ = *config;\n target_bitrate_kbps_ = config_.startBitrate;\n return 0;\n}\n\nint32_t FakeEncoder::Encode(const VideoFrame& input_image,\n const CodecSpecificInfo* codec_specific_info,\n const std::vector* frame_types) {\n assert(config_.maxFramerate > 0);\n int64_t time_since_last_encode_ms = 1000 \/ config_.maxFramerate;\n int64_t time_now_ms = clock_->TimeInMilliseconds();\n const bool first_encode = last_encode_time_ms_ == 0;\n if (!first_encode) {\n \/\/ For all frames but the first we can estimate the display time by looking\n \/\/ at the display time of the previous frame.\n time_since_last_encode_ms = time_now_ms - last_encode_time_ms_;\n }\n\n size_t bits_available =\n static_cast(target_bitrate_kbps_ * time_since_last_encode_ms);\n size_t min_bits = static_cast(\n config_.simulcastStream[0].minBitrate * time_since_last_encode_ms);\n if (bits_available < min_bits)\n bits_available = min_bits;\n size_t max_bits =\n static_cast(max_target_bitrate_kbps_ * time_since_last_encode_ms);\n if (max_bits > 0 && max_bits < bits_available)\n bits_available = max_bits;\n last_encode_time_ms_ = time_now_ms;\n\n assert(config_.numberOfSimulcastStreams > 0);\n for (unsigned char i = 0; i < config_.numberOfSimulcastStreams; ++i) {\n CodecSpecificInfo specifics;\n memset(&specifics, 0, sizeof(specifics));\n specifics.codecType = kVideoCodecGeneric;\n specifics.codecSpecific.generic.simulcast_idx = i;\n size_t min_stream_bits = static_cast(\n config_.simulcastStream[i].minBitrate * time_since_last_encode_ms);\n size_t max_stream_bits = static_cast(\n config_.simulcastStream[i].maxBitrate * time_since_last_encode_ms);\n size_t stream_bits = (bits_available > max_stream_bits) ? max_stream_bits :\n bits_available;\n size_t stream_bytes = (stream_bits + 7) \/ 8;\n if (first_encode) {\n \/\/ The first frame is a key frame and should be larger.\n \/\/ TODO(holmer): The FakeEncoder should store the bits_available between\n \/\/ encodes so that it can compensate for oversized frames.\n stream_bytes *= 10;\n }\n if (stream_bytes > sizeof(encoded_buffer_))\n stream_bytes = sizeof(encoded_buffer_);\n\n EncodedImage encoded(\n encoded_buffer_, stream_bytes, sizeof(encoded_buffer_));\n encoded._timeStamp = input_image.timestamp();\n encoded.capture_time_ms_ = input_image.render_time_ms();\n encoded._frameType = (*frame_types)[i];\n \/\/ Always encode something on the first frame.\n if (min_stream_bits > bits_available && i > 0) {\n encoded._length = 0;\n encoded._frameType = kSkipFrame;\n }\n assert(callback_ != NULL);\n if (callback_->Encoded(encoded, &specifics, NULL) != 0)\n return -1;\n bits_available -= std::min(encoded._length * 8, bits_available);\n }\n return 0;\n}\n\nint32_t FakeEncoder::RegisterEncodeCompleteCallback(\n EncodedImageCallback* callback) {\n callback_ = callback;\n return 0;\n}\n\nint32_t FakeEncoder::Release() { return 0; }\n\nint32_t FakeEncoder::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {\n return 0;\n}\n\nint32_t FakeEncoder::SetRates(uint32_t new_target_bitrate, uint32_t framerate) {\n target_bitrate_kbps_ = new_target_bitrate;\n return 0;\n}\n\nFakeH264Encoder::FakeH264Encoder(Clock* clock)\n : FakeEncoder(clock), callback_(NULL), idr_counter_(0) {\n FakeEncoder::RegisterEncodeCompleteCallback(this);\n}\n\nint32_t FakeH264Encoder::RegisterEncodeCompleteCallback(\n EncodedImageCallback* callback) {\n callback_ = callback;\n return 0;\n}\n\nint32_t FakeH264Encoder::Encoded(const EncodedImage& encoded_image,\n const CodecSpecificInfo* codec_specific_info,\n const RTPFragmentationHeader* fragments) {\n const size_t kSpsSize = 8;\n const size_t kPpsSize = 11;\n const int kIdrFrequency = 10;\n RTPFragmentationHeader fragmentation;\n if (idr_counter_++ % kIdrFrequency == 0 &&\n encoded_image._length > kSpsSize + kPpsSize + 1) {\n const size_t kNumSlices = 3;\n fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);\n fragmentation.fragmentationOffset[0] = 0;\n fragmentation.fragmentationLength[0] = kSpsSize;\n fragmentation.fragmentationOffset[1] = kSpsSize;\n fragmentation.fragmentationLength[1] = kPpsSize;\n fragmentation.fragmentationOffset[2] = kSpsSize + kPpsSize;\n fragmentation.fragmentationLength[2] =\n encoded_image._length - (kSpsSize + kPpsSize);\n const size_t kSpsNalHeader = 0x67;\n const size_t kPpsNalHeader = 0x68;\n const size_t kIdrNalHeader = 0x65;\n encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kSpsNalHeader;\n encoded_image._buffer[fragmentation.fragmentationOffset[1]] = kPpsNalHeader;\n encoded_image._buffer[fragmentation.fragmentationOffset[2]] = kIdrNalHeader;\n } else {\n const size_t kNumSlices = 1;\n fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);\n fragmentation.fragmentationOffset[0] = 0;\n fragmentation.fragmentationLength[0] = encoded_image._length;\n const size_t kNalHeader = 0x41;\n encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kNalHeader;\n }\n uint8_t value = 0;\n int fragment_counter = 0;\n for (size_t i = 0; i < encoded_image._length; ++i) {\n if (fragment_counter == fragmentation.fragmentationVectorSize ||\n i != fragmentation.fragmentationOffset[fragment_counter]) {\n encoded_image._buffer[i] = value++;\n } else {\n ++fragment_counter;\n }\n }\n return callback_->Encoded(encoded_image, NULL, &fragmentation);\n}\n\nDelayedEncoder::DelayedEncoder(Clock* clock, int delay_ms)\n : test::FakeEncoder(clock),\n delay_ms_(delay_ms) {}\n\nint32_t DelayedEncoder::Encode(const VideoFrame& input_image,\n const CodecSpecificInfo* codec_specific_info,\n const std::vector* frame_types) {\n SleepMs(delay_ms_);\n return FakeEncoder::Encode(input_image, codec_specific_info, frame_types);\n}\n} \/\/ namespace test\n} \/\/ namespace webrtc\n","avg_line_length":37.904040404,"max_line_length":80,"alphanum_fraction":0.7164556962} {"size":860,"ext":"cpp","lang":"C++","max_stars_count":3.0,"content":"#include \n#include \n#include \n#include \"tmwtypes.h\"\n#include \"stdlib.h\"\n\nusing namespace std;\n\n\/\/ Genereate Gaussian R.V\n\/\/ using fstream store R.V in a txt file.\n\nint main() {\n\t\/\/ random seed.\n\tsrand(2);\n\t\n\t\/\/ length of sequence.\n\tint n = 1364*2;\n\n\tdouble x1[n], x2[n], x3[n], x4[n], x5[n];\n\tdouble y[n];\n\t\n\tfor (int i = 0; i < n; i++) {\n\t\tx1[i] = (double)rand() \/ (double)RAND_MAX;\n\t\tx2[i] = (double)rand() \/ (double)RAND_MAX;\n\t\tx3[i] = (double)rand() \/ (double)RAND_MAX;\n\t\tx4[i] = (double)rand() \/ (double)RAND_MAX;\n\t\tx5[i] = (double)rand() \/ (double)RAND_MAX;\n\t\n\t\ty[i] = (x1[i] + x2[i] + x3[i] + x4[i] + x5[i]) \/ n;\n\t}\n\t\n\t\/\/ write file.\n\tofstream outfile(\"gnoise.txt\");\n\t\n\tint i=0;\n\tfor (i = 0; i < n; i++) {\n\t\toutfile << y[i] << \"\\n\";\n\t}\n\n\tcout << \"Size of Gaussian Noise file: \" << i << \"\\n\";\n\t\n\toutfile.close();\n\t\n\treturn 0;\n}\n","avg_line_length":18.6956521739,"max_line_length":54,"alphanum_fraction":0.5593023256} {"size":1255,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n#include \"AnythingLookupPathResultMapper.h\"\n#include \"Tracer.h\"\n\n\/\/---- AnythingLookupPathResultMapper ----------------------------------------------------------------\nRegisterResultMapper(AnythingLookupPathResultMapper);\n\nbool AnythingLookupPathResultMapper::DoPutAnyWithSlotname(const char *key, Anything &value, Context &ctx, ROAnything roaScript, const char *slotname)\n{\n\tStartTrace1(AnythingLookupPathResultMapper.DoPutAnyWithSlotname, \"key [\" << NotNull(key) << \"] slotname [\" << NotNull(slotname) << \"]\");\n\tTrace(\"Using slotname [\" << slotname << \"] as Lookup path in value\");\n\tbool bRet = true;\t\/\/ do not fail when lookup fails!\n\tAnything anyValue;\n\tif ( value.LookupPath(anyValue, slotname) ) {\n\t\tTraceAny(anyValue, \"Calling myself again with Anything looked up at [\" << slotname << \"]\");\n\t\tbRet = DoPutAny(key, anyValue, ctx, roaScript);\n\t\tTrace(\"RetCode of DoPutAny:\" << (bRet ? \"true\" : \"false\"));\n\t}\n\treturn bRet;\n}\n","avg_line_length":44.8214285714,"max_line_length":149,"alphanum_fraction":0.6980079681} {"size":2729,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/*\n\/\/@HEADER\n\/\/ ************************************************************************\n\/\/\n\/\/ KokkosKernels 0.9: Linear Algebra and Graph Kernels\n\/\/ Copyright 2017 Sandia Corporation\n\/\/\n\/\/ Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n\/\/ the U.S. Government retains certain rights in this software.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ 3. Neither the name of the Corporation nor the names of the\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION \"AS IS\" AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Questions? Contact Siva Rajamanickam (srajama@sandia.gov)\n\/\/\n\/\/ ************************************************************************\n\/\/@HEADER\n*\/\n\n\n#define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true\n#include \"KokkosKernels_config.h\"\n\n#if defined (KOKKOSKERNELS_INST_KOKKOS_COMPLEX_DOUBLE_) \\\n && defined (KOKKOSKERNELS_INST_LAYOUTLEFT) \\\n && defined (KOKKOSKERNELS_INST_EXECSPACE_THREADS) \\\n && defined (KOKKOSKERNELS_INST_MEMSPACE_HOSTSPACE) \\\n && defined (KOKKOSKERNELS_INST_MEMSPACE_HOSTSPACE) \\\n && defined (KOKKOSKERNELS_INST_ORDINAL_INT64_T) \\\n && defined (KOKKOSKERNELS_INST_OFFSET_SIZE_T) \n#include \"KokkosSparse_spgemm_symbolic_spec.hpp\"\nnamespace KokkosSparse {\nnamespace Impl {\n KOKKOSSPARSE_SPGEMM_SYMBOLIC_ETI_SPEC_INST(Kokkos::complex, int64_t, size_t, Kokkos::LayoutLeft, Kokkos::Threads, Kokkos::HostSpace, Kokkos::HostSpace)\n} \/\/ Impl\n} \/\/ KokkosSparse\n#endif\n","avg_line_length":44.0161290323,"max_line_length":160,"alphanum_fraction":0.7299377061} {"size":6817,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \"Sarene.h\"\n\n#include \"Platform\/OpenGL\/OpenGLShader.h\"\n\n#include \"imgui\/imgui.h\"\n#include \n#include \n\nclass ExampleLayer : public Sarene::Layer\n{\npublic:\n\tExampleLayer()\n\t\t: Layer(\"Example\"), m_Camera(-1.6f, 1.6f, -0.9f, 0.9f), m_CameraPosition(0.0f)\n\t{\n\t\tm_VertexArray.reset(Sarene::VertexArray::Create());\n\n\t\tfloat vertices[3 * 7] = {\n\t\t\t-0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,\n\t\t\t 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f,\n\t\t\t 0.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f\n\t\t};\n\n\t\tSarene::Ref vertexBuffer;\n\t\tvertexBuffer.reset(Sarene::VertexBuffer::Create(vertices, sizeof(vertices)));\n\n\t\tSarene::BufferLayout layout = {\n\t\t\t{ Sarene::ShaderDataType::Float3, \"a_Position\" },\n\t\t\t{ Sarene::ShaderDataType::Float4, \"a_Color\" }\n\t\t};\n\n\t\tvertexBuffer->SetLayout(layout);\n\t\tm_VertexArray->AddVertexBuffer(vertexBuffer);\n\n\t\tunsigned int indices[3] = { 0, 1, 2 };\n\t\tSarene::Ref indexBuffer;\n\t\tindexBuffer.reset(Sarene::IndexBuffer::Create(indices, sizeof(indices) \/ sizeof(uint32_t)));\n\t\tm_VertexArray->SetIndexBuffer(indexBuffer);\n\n\t\tm_SquareVA.reset(Sarene::VertexArray::Create());\n\n\t\tfloat squareVertices[5 * 4] = {\n\t\t\t-0.75f, -0.75f, 0.0f, 0.0f, 0.0f,\n\t\t\t 0.75f, -0.75f, 0.0f, 1.0f, 0.0f,\n\t\t\t 0.75f, 0.75f, 0.0f, 1.0f, 1.0f,\n\t\t\t-0.75f, 0.75f, 0.0f, 0.0f, 1.0f\n\t\t};\n\n\t\tSarene::Ref squareVB;\n\t\tsquareVB.reset(Sarene::VertexBuffer::Create(squareVertices, sizeof(squareVertices)));\n\t\tsquareVB->SetLayout({\n\t\t\t\t{ Sarene::ShaderDataType::Float3, \"a_Position\" },\n\t\t\t\t{ Sarene::ShaderDataType::Float2, \"a_TexCoord\" }\n\t\t\t});\n\t\tm_SquareVA->AddVertexBuffer(squareVB);\n\n\t\tuint32_t squareIndices[6] = { 0, 1, 2, 2, 3, 0 };\n\t\tSarene::Ref squareIB;\n\t\tsquareIB.reset(Sarene::IndexBuffer::Create(squareIndices, sizeof(squareIndices) \/ sizeof(uint32_t)));\n\t\tm_SquareVA->SetIndexBuffer(squareIB);\n\n\t\tstd::string vertexSrc = R\"(\n\t\t\t#version 330 core\n\n\t\t\tlayout(location = 0) in vec3 a_Position;\n\t\t\tlayout(location = 1) in vec4 a_Color;\n\n\t\t\tuniform mat4 u_ViewProjection;\n\t\t\tuniform mat4 u_Transform;\n\n\t\t\tout vec3 v_Position;\n\t\t\tout vec4 v_Color;\n\n\t\t\tvoid main()\n\t\t\t{\n\t\t\t\tv_Position = a_Position;\n\t\t\t\tv_Color = a_Color;\n\t\t\t\tgl_Position = u_ViewProjection * u_Transform * vec4(a_Position, 1.0);\n\t\t\t}\n\t\t)\";\n\n\t\tstd::string fragmentSrc = R\"(\n\t\t\t#version 330 core\n\n\t\t\tlayout(location = 0) out vec4 color;\n\n\t\t\tin vec3 v_Position;\n\t\t\tin vec4 v_Color;\n\n\t\t\tvoid main()\n\t\t\t{\n\t\t\t\tcolor = vec4(v_Position * 0.5 + 0.5, 1.0);\n\t\t\t\tcolor = v_Color;\n\t\t\t}\n\t\t)\";\n\n\t\tm_Shader.reset(Sarene::Shader::Create(vertexSrc, fragmentSrc));\n\n\t\tstd::string flatColorShaderVertexSrc = R\"(\n\t\t\t#version 330 core\n\t\t\t\n\t\t\tlayout(location = 0) in vec3 a_Position;\n\t\t\tuniform mat4 u_ViewProjection;\n\t\t\tuniform mat4 u_Transform;\n\t\t\tout vec3 v_Position;\n\t\t\tvoid main()\n\t\t\t{\n\t\t\t\tv_Position = a_Position;\n\t\t\t\tgl_Position = u_ViewProjection * u_Transform * vec4(a_Position, 1.0);\t\n\t\t\t}\n\t\t)\";\n\n\t\tstd::string flatColorShaderFragmentSrc = R\"(\n\t\t\t#version 330 core\n\t\t\t\n\t\t\tlayout(location = 0) out vec4 color;\n\t\t\tin vec3 v_Position;\n\t\t\t\n\t\t\tuniform vec3 u_Color;\n\t\t\tvoid main()\n\t\t\t{\n\t\t\t\tcolor = vec4(u_Color, 1.0);\n\t\t\t}\n\t\t)\";\n\n\t\tm_FlatColorShader.reset(Sarene::Shader::Create(flatColorShaderVertexSrc, flatColorShaderFragmentSrc));\n\n\t\tstd::string textureShaderVertexSrc = R\"(\n\t\t\t#version 330 core\n\t\t\t\n\t\t\tlayout(location = 0) in vec3 a_Position;\n\t\t\tlayout(location = 1) in vec2 a_TexCoord;\n\t\t\tuniform mat4 u_ViewProjection;\n\t\t\tuniform mat4 u_Transform;\n\t\t\tout vec2 v_TexCoord;\n\t\t\tvoid main()\n\t\t\t{\n\t\t\t\tv_TexCoord = a_TexCoord;\n\t\t\t\tgl_Position = u_ViewProjection * u_Transform * vec4(a_Position, 1.0);\t\n\t\t\t}\n\t\t)\";\n\n\t\tstd::string textureShaderFragmentSrc = R\"(\n\t\t\t#version 330 core\n\t\t\t\n\t\t\tlayout(location = 0) out vec4 color;\n\t\t\tin vec2 v_TexCoord;\n\t\t\t\n\t\t\tuniform sampler2D u_Texture;\n\t\t\tvoid main()\n\t\t\t{\n\t\t\t\tcolor = texture(u_Texture, v_TexCoord);\n\t\t\t}\n\t\t)\";\n\n\t\tm_TextureShader.reset(Sarene::Shader::Create(textureShaderVertexSrc, textureShaderFragmentSrc));\n\n\t\tm_Texture = Sarene::Texture2D::Create(\"assets\/textures\/Checkerboard.png\");\n\n\t\tstd::dynamic_pointer_cast(m_TextureShader)->Bind();\n\t\tstd::dynamic_pointer_cast(m_TextureShader)->UploadUniformInt(\"u_Texture\", 0);\n\t}\n\n\tvoid OnUpdate(Sarene::Timestep ts) override\n\t{\n\t\tif (Sarene::Input::IsKeyPressed(SAR_KEY_LEFT))\n\t\t\tm_CameraPosition.x -= m_CameraMoveSpeed * ts;\n\t\telse if (Sarene::Input::IsKeyPressed(SAR_KEY_RIGHT))\n\t\t\tm_CameraPosition.x += m_CameraMoveSpeed * ts;\n\n\t\tif (Sarene::Input::IsKeyPressed(SAR_KEY_UP))\n\t\t\tm_CameraPosition.y += m_CameraMoveSpeed * ts;\n\t\telse if (Sarene::Input::IsKeyPressed(SAR_KEY_DOWN))\n\t\t\tm_CameraPosition.y -= m_CameraMoveSpeed * ts;\n\n\t\tif (Sarene::Input::IsKeyPressed(SAR_KEY_A))\n\t\t\tm_CameraRotation += m_CameraRotationSpeed * ts;\n\t\telse if (Sarene::Input::IsKeyPressed(SAR_KEY_D))\n\t\t\tm_CameraRotation -= m_CameraRotationSpeed * ts;\n\n\t\tSarene::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 });\n\t\tSarene::RenderCommand::Clear();\n\n\t\tm_Camera.SetPosition(m_CameraPosition);\n\t\tm_Camera.SetRotation(m_CameraRotation);\n\n\t\tSarene::Renderer::BeginScene(m_Camera);\n\n\t\tglm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(0.1f));\n\n\t\tstd::dynamic_pointer_cast(m_FlatColorShader)->Bind();\n\t\tstd::dynamic_pointer_cast(m_FlatColorShader)->UploadUniformFloat3(\"u_Color\", m_SquareColor);\n\n\t\tfor (int y = 0; y < 20; y++)\n\t\t{\n\t\t\tfor (int x = 0; x < 20; x++)\n\t\t\t{\n\t\t\t\tglm::vec3 pos(x * 0.16f, y * 0.16f, 0.0f);\n\t\t\t\tglm::mat4 transform = glm::translate(glm::mat4(1.0f), pos) * scale;\n\t\t\t\tSarene::Renderer::Submit(m_FlatColorShader, m_SquareVA, transform);\n\t\t\t}\n\t\t}\n\n\t\tm_Texture->Bind();\n\t\tSarene::Renderer::Submit(m_TextureShader, m_SquareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.0f)));\n\n\t\t\/\/Sarene::Renderer::Submit(m_Shader, m_VertexArray);\n\n\t\tSarene::Renderer::EndScene();\n\t}\n\n\tvirtual void OnImGuiRender() override\n\t{\n\t\tImGui::Begin(\"Settings\");\n\t\tImGui::ColorEdit3(\"Square Color\", glm::value_ptr(m_SquareColor));\n\t\tImGui::End();\n\t}\n\n\tvoid OnEvent(Sarene::Event& event) override\n\t{\n\n\t}\nprivate:\n\tSarene::Ref m_Shader;\n\tSarene::Ref m_VertexArray;\n\n\tSarene::Ref m_FlatColorShader, m_TextureShader;\n\tSarene::Ref m_SquareVA;\n\n\tSarene::Ref m_Texture;\n\n\tSarene::OrthographicCamera m_Camera;\n\tglm::vec3 m_CameraPosition;\n\tfloat m_CameraMoveSpeed = 5.0f;\n\n\tfloat m_CameraRotation = 0.0f;\n\tfloat m_CameraRotationSpeed = 180.0f;\n\n\tglm::vec3 m_SquareColor = { 0.2f, 0.3f, 0.8f };\n};\n\nclass Sandbox : public Sarene::Application\n{\npublic:\n\tSandbox()\n\t{\n\t\tPushLayer(new ExampleLayer());\n\t}\n\n\t~Sandbox()\n\t{\n\n\t}\n};\n\nSarene::Application* Sarene::CreateApplication()\n{\n\treturn new Sandbox();\n}","avg_line_length":26.4224806202,"max_line_length":116,"alphanum_fraction":0.6897462227} {"size":1651,"ext":"cpp","lang":"C++","max_stars_count":519.0,"content":"\/\/ BSD 3-Clause License; see https:\/\/github.com\/scikit-hep\/awkward-1.0\/blob\/main\/LICENSE\n\n#define FILENAME(line) FILENAME_FOR_EXCEPTIONS_C(\"src\/cpu-kernels\/awkward_MaskedArray_getitem_next_jagged_project.cpp\", line)\n\n#include \"awkward\/kernels.h\"\n\ntemplate \nERROR awkward_MaskedArray_getitem_next_jagged_project(\n T* index,\n int64_t* starts_in,\n int64_t* stops_in,\n int64_t* starts_out,\n int64_t* stops_out,\n int64_t length) {\n int64_t k = 0;\n for (int64_t i = 0; i < length; ++i) {\n if (index[i] >= 0) {\n starts_out[k] = starts_in[i];\n stops_out[k] = stops_in[i];\n k++;\n }\n }\n return success();\n}\nERROR awkward_MaskedArray32_getitem_next_jagged_project(\n int32_t* index,\n int64_t* starts_in,\n int64_t* stops_in,\n int64_t* starts_out,\n int64_t* stops_out,\n int64_t length) {\n return awkward_MaskedArray_getitem_next_jagged_project(\n index,\n starts_in,\n stops_in,\n starts_out,\n stops_out,\n length);\n}\nERROR awkward_MaskedArrayU32_getitem_next_jagged_project(\n uint32_t* index,\n int64_t* starts_in,\n int64_t* stops_in,\n int64_t* starts_out,\n int64_t* stops_out,\n int64_t length) {\n return awkward_MaskedArray_getitem_next_jagged_project(\n index,\n starts_in,\n stops_in,\n starts_out,\n stops_out,\n length);\n}\nERROR awkward_MaskedArray64_getitem_next_jagged_project(\n int64_t* index,\n int64_t* starts_in,\n int64_t* stops_in,\n int64_t* starts_out,\n int64_t* stops_out,\n int64_t length) {\n return awkward_MaskedArray_getitem_next_jagged_project(\n index,\n starts_in,\n stops_in,\n starts_out,\n stops_out,\n length);\n}\n","avg_line_length":23.5857142857,"max_line_length":125,"alphanum_fraction":0.7244094488} {"size":6258,"ext":"cc","lang":"C++","max_stars_count":2151.0,"content":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"third_party\/blink\/renderer\/platform\/graphics\/paint\/paint_controller.h\"\n\n#include \"third_party\/blink\/renderer\/platform\/graphics\/paint\/drawing_display_item.h\"\n\n#if DCHECK_IS_ON()\n\nnamespace blink {\n\nclass PaintController::DisplayItemListAsJSON {\n STACK_ALLOCATED();\n\n public:\n DisplayItemListAsJSON(const DisplayItemList&,\n const CachedSubsequenceMap&,\n const Vector&,\n DisplayItemList::JsonFlags);\n\n String ToString() {\n return SubsequenceAsJSONArrayRecursive(0, list_.size())\n ->ToPrettyJSONString();\n }\n\n private:\n std::unique_ptr SubsequenceAsJSONObjectRecursive();\n std::unique_ptr SubsequenceAsJSONArrayRecursive(size_t, size_t);\n void AppendSubsequenceAsJSON(size_t, size_t, JSONArray&);\n String ClientName(const DisplayItemClient&) const;\n\n struct SubsequenceInfo {\n SubsequenceInfo(const DisplayItemClient* client, size_t start, size_t end)\n : client(client), start(start), end(end) {}\n const DisplayItemClient* client;\n size_t start;\n size_t end;\n };\n\n const DisplayItemList& list_;\n Vector subsequences_;\n Vector::const_iterator current_subsequence_;\n const Vector& chunks_;\n Vector::const_iterator current_chunk_;\n DisplayItemList::JsonFlags flags_;\n};\n\nPaintController::DisplayItemListAsJSON::DisplayItemListAsJSON(\n const DisplayItemList& list,\n const CachedSubsequenceMap& subsequence_map,\n const Vector& chunks,\n DisplayItemList::JsonFlags flags)\n : list_(list),\n chunks_(chunks),\n current_chunk_(chunks.begin()),\n flags_(flags) {\n for (const auto& item : subsequence_map) {\n subsequences_.push_back(\n SubsequenceInfo(item.key, item.value.start, item.value.end));\n }\n std::sort(subsequences_.begin(), subsequences_.end(),\n [](const SubsequenceInfo& a, const SubsequenceInfo& b) {\n return a.start == b.start ? a.end > b.end : a.start < b.start;\n });\n\n current_subsequence_ = subsequences_.begin();\n}\n\nstd::unique_ptr\nPaintController::DisplayItemListAsJSON::SubsequenceAsJSONObjectRecursive() {\n const auto& subsequence = *current_subsequence_;\n ++current_subsequence_;\n\n auto json_object = JSONObject::Create();\n\n json_object->SetString(\"subsequence\",\n String::Format(\"client: %p \", subsequence.client) +\n ClientName(*subsequence.client));\n json_object->SetArray(\n RuntimeEnabledFeatures::SlimmingPaintV175Enabled() ? \"chunks\"\n : \"displayItems\",\n SubsequenceAsJSONArrayRecursive(subsequence.start, subsequence.end));\n\n return json_object;\n}\n\nstd::unique_ptr\nPaintController::DisplayItemListAsJSON::SubsequenceAsJSONArrayRecursive(\n size_t start_item,\n size_t end_item) {\n std::unique_ptr array = JSONArray::Create();\n size_t item_index = start_item;\n\n while (current_subsequence_ != subsequences_.end() &&\n current_subsequence_->start < end_item) {\n const auto& subsequence = *current_subsequence_;\n DCHECK(subsequence.start >= item_index);\n DCHECK(subsequence.end <= end_item);\n\n if (item_index < subsequence.start)\n AppendSubsequenceAsJSON(item_index, subsequence.start, *array);\n array->PushObject(SubsequenceAsJSONObjectRecursive());\n item_index = subsequence.end;\n }\n\n if (item_index < end_item)\n AppendSubsequenceAsJSON(item_index, end_item, *array);\n\n return array;\n}\n\nvoid PaintController::DisplayItemListAsJSON::AppendSubsequenceAsJSON(\n size_t start_item,\n size_t end_item,\n JSONArray& json_array) {\n DCHECK(end_item > start_item);\n\n if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) {\n list_.AppendSubsequenceAsJSON(start_item, end_item, flags_, json_array);\n return;\n }\n\n DCHECK(current_chunk_ != chunks_.end());\n DCHECK(current_chunk_->begin_index == start_item);\n\n while (current_chunk_ != chunks_.end() &&\n current_chunk_->end_index <= end_item) {\n const auto& chunk = *current_chunk_;\n auto json_object = JSONObject::Create();\n\n json_object->SetString(\n \"chunk\", ClientName(chunk.id.client) + \" \" + chunk.id.ToString());\n json_object->SetString(\"state\", chunk.properties.ToString());\n if (flags_ & DisplayItemList::kShowPaintRecords)\n json_object->SetString(\"chunkData\", chunk.ToString());\n\n json_object->SetArray(\n \"displayItems\",\n list_.SubsequenceAsJSON(chunk.begin_index, chunk.end_index, flags_));\n\n json_array.PushObject(std::move(json_object));\n ++current_chunk_;\n }\n}\n\nString PaintController::DisplayItemListAsJSON::ClientName(\n const DisplayItemClient& client) const {\n return DisplayItemClient::SafeDebugName(\n client, flags_ & DisplayItemList::kClientKnownToBeAlive);\n}\n\nvoid PaintController::ShowDebugDataInternal(\n DisplayItemList::JsonFlags flags) const {\n LOG(ERROR) << \"current display item list: \"\n << DisplayItemListAsJSON(\n current_paint_artifact_.GetDisplayItemList(),\n current_cached_subsequences_,\n current_paint_artifact_.PaintChunks(), flags)\n .ToString()\n .Utf8()\n .data();\n\n LOG(ERROR) << \"new display item list: \"\n << DisplayItemListAsJSON(\n new_display_item_list_, new_cached_subsequences_,\n new_paint_chunks_.PaintChunks(),\n \/\/ The clients in new_display_item_list_ are all alive.\n flags | DisplayItemList::kClientKnownToBeAlive)\n .ToString()\n .Utf8()\n .data();\n}\n\nvoid PaintController::ShowDebugData() const {\n return ShowDebugDataInternal(DisplayItemList::kDefault);\n}\n\nvoid PaintController::ShowDebugDataWithRecords() const {\n return ShowDebugDataInternal(DisplayItemList::kShowPaintRecords);\n}\n\n} \/\/ namespace blink\n\n#endif \/\/ DCHECK_IS_ON()\n","avg_line_length":33.6451612903,"max_line_length":84,"alphanum_fraction":0.6880792585} {"size":830,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \nusing namespace std;\nclass CB1\n{\npublic:\n\tint a; \/\/\u91cd\u540d\n\tCB1(int x)\n\t{ \n\t\ta = x;\n\t}\t\n\tvoid showa() \/\/\u91cd\u540d\n\t{\n\t\tcout << \"Class CB1 ==> a =\" << a << endl;\n\t}\n};\n\nclass CB2\n{\npublic:\n\tint a; \/\/\u91cd\u540d\n\tCB2(int x)\n\t{\n\t\ta = x;\n\t}\n\tvoid showa() \/\/\u91cd\u540d\n\t{\n\t\tcout << \"Class CB2 ==> a = \" << a << endl;\n\t}\n};\n\nclass CD:public CB1, public CB2\n{\npublic:\n\tint a;\n\tCD(int x, int y, int z):CB1(x),CB2(y)\n\t{\n\t\ta = z;\n\t}\n\tvoid showa() \/\/\u4e0e\u4e24\u4e2a\u57fa\u7c7b\u6210\u5458\u51fd\u6570showa()\u91cd\u540d\n\t{\n\t\tcout << \"Class CD ==> a =\" << a << endl;\n\t}\n\tvoid print3a()\n\t{\n\t\tcout << \"a = \" << a << endl;\n\t\tcout << \"CB1::a =\" << CB1::a << endl;\n\t\tcout << \"CB2::a =\" << CB2::a << endl;\n\t}\n};\n\nint main()\n{\n\tCB1 CB1obj(11);\n\tCB1obj.showa();\n\tCD CDobj(101, 202, 909);\n\tCDobj.showa();\n\tcout << \"CDobj.a =\" << CDobj.a << endl;\n\tcout << \"CDobj.CB2::a\" << CDobj.CB2::a << endl;\n\treturn 0;\n}\n\t\n\n","avg_line_length":13.1746031746,"max_line_length":48,"alphanum_fraction":0.4939759036} {"size":2697,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/****************************************************************************\n** Meta object code from reading C++ file 'csvmodelwriter.h'\n**\n** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.1)\n**\n** WARNING! All changes made in this file will be lost!\n*****************************************************************************\/\n\n#include \"..\/src\/qt\/csvmodelwriter.h\"\n#include \n#include \n#if !defined(Q_MOC_OUTPUT_REVISION)\n#error \"The header file 'csvmodelwriter.h' doesn't include .\"\n#elif Q_MOC_OUTPUT_REVISION != 67\n#error \"This file was generated using the moc from 5.7.1. It\"\n#error \"cannot be used with the include files from this version of Qt.\"\n#error \"(The moc has changed too much.)\"\n#endif\n\nQT_BEGIN_MOC_NAMESPACE\nstruct qt_meta_stringdata_CSVModelWriter_t {\n QByteArrayData data[1];\n char stringdata0[15];\n};\n#define QT_MOC_LITERAL(idx, ofs, len) \\\n Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \\\n qptrdiff(offsetof(qt_meta_stringdata_CSVModelWriter_t, stringdata0) + ofs \\\n - idx * sizeof(QByteArrayData)) \\\n )\nstatic const qt_meta_stringdata_CSVModelWriter_t qt_meta_stringdata_CSVModelWriter = {\n {\nQT_MOC_LITERAL(0, 0, 14) \/\/ \"CSVModelWriter\"\n\n },\n \"CSVModelWriter\"\n};\n#undef QT_MOC_LITERAL\n\nstatic const uint qt_meta_data_CSVModelWriter[] = {\n\n \/\/ content:\n 7, \/\/ revision\n 0, \/\/ classname\n 0, 0, \/\/ classinfo\n 0, 0, \/\/ methods\n 0, 0, \/\/ properties\n 0, 0, \/\/ enums\/sets\n 0, 0, \/\/ constructors\n 0, \/\/ flags\n 0, \/\/ signalCount\n\n 0 \/\/ eod\n};\n\nvoid CSVModelWriter::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)\n{\n Q_UNUSED(_o);\n Q_UNUSED(_id);\n Q_UNUSED(_c);\n Q_UNUSED(_a);\n}\n\nconst QMetaObject CSVModelWriter::staticMetaObject = {\n { &QObject::staticMetaObject, qt_meta_stringdata_CSVModelWriter.data,\n qt_meta_data_CSVModelWriter, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}\n};\n\n\nconst QMetaObject *CSVModelWriter::metaObject() const\n{\n return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;\n}\n\nvoid *CSVModelWriter::qt_metacast(const char *_clname)\n{\n if (!_clname) return Q_NULLPTR;\n if (!strcmp(_clname, qt_meta_stringdata_CSVModelWriter.stringdata0))\n return static_cast(const_cast< CSVModelWriter*>(this));\n return QObject::qt_metacast(_clname);\n}\n\nint CSVModelWriter::qt_metacall(QMetaObject::Call _c, int _id, void **_a)\n{\n _id = QObject::qt_metacall(_c, _id, _a);\n if (_id < 0)\n return _id;\n return _id;\n}\nQT_END_MOC_NAMESPACE\n","avg_line_length":29.9666666667,"max_line_length":96,"alphanum_fraction":0.6499814609} {"size":3858,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \"Image\/motionAlgorithms\/IAlertAlgorithm.hpp\"\n#include \"Image\/private\/CRingBuffer.hpp\"\n\nCImageBuffer::CRingBuffer::CRingBuffer(int size, int longSize, int longSkipCount, const std::string& info)\n : mMaxSize(size)\n , mMaxLongSize(longSize)\n , mLongSkipCount(longSkipCount)\n , mInfoStr(info)\n , mId(0)\n , mLongId(0)\n{\n}\n\nCImageBuffer::CRingBuffer::~CRingBuffer()\n{\n std::lock_guard lock(mMutex);\n int initCount = mList.size() - 1;\n for (int i = initCount; i < initCount - NAlgorithms::IAlertAlgorithm::sMinAlgoFrameCount; i--)\n {\n if (i >= 0)\n {\n mList[i]->decreaseRefCounter();\n }\n }\n}\n\nbool CImageBuffer::CRingBuffer::isFull() const\n{\n return mList.size() >= mMaxSize;\n}\n\nvoid CImageBuffer::CRingBuffer::push_back(const pMatWithTimeStamp elem)\n{\n std::lock_guard lock(mMutex);\n mList.push_back(elem);\n\n if (mList.size() > mMaxSize)\n {\n mList.front()->decreaseRefCounter();\n\n if ((mMaxLongSize > 0 && (mLongSkipCount > 0) && (mLongId++ %mLongSkipCount == 0))\n || mLongList.size() < mMaxLongSize)\n {\n mLongList.push_back(mList.front());\n if (mLongList.size() > mMaxLongSize)\n {\n mLongList.pop_front();\n }\n }\n mList.pop_front();\n }\n\n static const int sOffset = 1;\n if (mList.size() > (NAlgorithms::IAlertAlgorithm::sMinAlgoFrameCount + sOffset))\n {\n \/\/delete data for less mem ussage\n mList[mList.size() - (NAlgorithms::IAlertAlgorithm::sMinAlgoFrameCount + sOffset)]->decreaseRefCounter();\n }\n}\n\nint CImageBuffer::CRingBuffer::capacity() const\n{\n return mMaxSize;\n}\n\nbool CImageBuffer::CRingBuffer::empty() const\n{\n return mList.empty();\n}\n\nvoid CImageBuffer::CRingBuffer::clear()\n{\n std::lock_guard lock(mMutex);\n mList.clear();\n mLongList.clear();\n}\n\nint CImageBuffer::CRingBuffer::size() const\n{\n return mList.size();\n}\n\nint CImageBuffer::CRingBuffer::longSize() const\n{\n return mLongList.size();\n}\n\nsize_t CImageBuffer::CRingBuffer::getNextId()\n{\n return mId++;\n}\n\nvoid CImageBuffer::CRingBuffer::setHasAlert(bool alertStatus)\n{\n mIsHasAlert = alertStatus;\n if (alertStatus)\n {\n mLastAlertDt = QDateTime::currentDateTime();\n }\n}\n\nbool CImageBuffer::CRingBuffer::getHasAlert() const\n{\n return mIsHasAlert;\n}\n\nconst QDateTime&CImageBuffer::CRingBuffer::getLastAlertDt() const\n{\n return mLastAlertDt;\n}\n\nconst QList& CImageBuffer::CRingBuffer::getList() const\n{\n std::lock_guard lock(mMutex);\n return mList;\n}\n\nconst pMatWithTimeStamp CImageBuffer::CRingBuffer::operator[](int elementId) const\n{\n std::lock_guard lock(mMutex);\n if (elementId < 0 || elementId >= mList.size())\n {\n return nullptr;\n }\n return mList.at(elementId);\n}\n\nconst std::string& CImageBuffer::CRingBuffer::getInfo() const\n{\n return mInfoStr;\n}\n\nCImageBuffer::CRingBuffer::CRingBuffer(const CImageBuffer::CRingBuffer& other)\n{\nstd::lock_guard lock(mMutex);\n if (this != &other)\n {\n#define COPY(field) field = other.field\n COPY(mList);\n COPY(mLongList);\n COPY(mMaxSize);\n COPY(mMaxLongSize);\n COPY(mLongSkipCount);\n COPY(mInfoStr);\n COPY(mId);\n COPY(mLongId);\n }\n\n int initCount = mList.size() - 1;\n for (int i = initCount; i < initCount - NAlgorithms::IAlertAlgorithm::sMinAlgoFrameCount; i--)\n {\n if (i >= 0)\n {\n mList[i]->increaseRefCounter();\n }\n }\n}\n\nvoid CImageBuffer::CRingBuffer::setInfoStr(const std::string& infoStr)\n{\n mInfoStr = infoStr;\n}\n\nconst QList& CImageBuffer::CRingBuffer::getLongList() const\n{\n std::lock_guard lock(mMutex);\n return mLongList;\n}\n","avg_line_length":22.8284023669,"max_line_length":113,"alphanum_fraction":0.645930534} {"size":17937,"ext":"cc","lang":"C++","max_stars_count":6.0,"content":"\/\/ -*- C++ -*-\n\/\/\n\/\/ michael a.g. a\u00efv\u00e1zis \n\/\/ (c) 2013-2021 parasim inc\n\/\/ all rights reserved\n\/\/\n\n\/\/ configuration\n#include \n\/\/ external\n#include \n#include \n#include \n#include \n#include \n\n\/\/ my declarations\n#include \"Source.h\"\n\n\/\/ make pi\nconst auto pi = 4*std::atan(1.0);\n\n\/\/ meta-methods\n\/\/ constructor\naltar::models::cudacdm::Source::\nSource(size_type parameters, size_type samples, size_type observations, double nu):\n _nSamples(samples),\n _nParameters(parameters),\n _nObservations(observations),\n _nu(nu),\n _data(0),\n _locations(0),\n _los(0),\n _oids(0),\n _xIdx(0),\n _yIdx(0),\n _dIdx(0),\n _openingIdx(0),\n _aXIdx(0),\n _aYIdx(0),\n _aZIdx(0),\n _omegaXIdx(0),\n _omegaYIdx(0),\n _omegaZIdx(0),\n _offsetIdx(0),\n _samples(0),\n _predicted(0)\n{\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ compute the amount of memory required to hold the samples\n const size_type sampleFootprint = parameters * samples * sizeof(data_type);\n \/\/ allocate device memory for them\n cudaError_t status = cudaMallocManaged(&_samples, sampleFootprint);\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while allocating device memory for the parameter samples: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::bad_alloc();\n }\n \/\/ otherwise, tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"allocated an arena of \" << sampleFootprint << \" bytes for the samples\"\n << pyre::journal::endl;\n\n \/\/ compute the amount of memory required to hold the predicted displacements\n const size_type displacementsFootprint = samples * observations * sizeof(data_type);\n \/\/ allocate device memory for them\n status = cudaMallocManaged(&_predicted, displacementsFootprint);\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while allocating device memory for the predicted displacements: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::bad_alloc();\n }\n \/\/ otherwise, tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"allocated an arena of \" << displacementsFootprint\n << \" bytes for the predicted displacements\"\n << pyre::journal::endl;\n\n \/\/ compute the amount of memory needed to hold the data\n const size_type dataFootprint = _nObservations * sizeof(data_type);\n \/\/ allocate device memory for them\n status = cudaMallocManaged(&_data, dataFootprint);\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while allocating device memory for the observations: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::bad_alloc();\n }\n \/\/ otherwise, tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"allocated an arena of \" << dataFootprint << \" bytes for the observations\"\n << pyre::journal::endl;\n\n \/\/ we only have (x,y) coordinates for the observation points\n const int locDim = 2;\n \/\/ compute the memory footprint of the coordinates of the observation points\n const size_type locationsFootprint = locDim * _nObservations * sizeof(data_type);\n \/\/ allocate device memory for them\n status = cudaMallocManaged(&_locations, locationsFootprint);\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while allocating device memory for the location coordinates: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::bad_alloc();\n }\n \/\/ otherwise, tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"allocated an arena of \" << locationsFootprint << \" bytes for the observation locations\"\n << pyre::journal::endl;\n\n \/\/ we have the 3 components of the unit LOS vectors to the observation point on the ground\n const int losDim = 3;\n \/\/ compute the memory footprint of the LOS unit vectors\n const size_type losFootprint = losDim * _nObservations * sizeof(data_type);\n \/\/ allocate device memory for them\n status = cudaMallocManaged(&_los, losFootprint);\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while allocating device memory for the location coordinates: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::bad_alloc();\n }\n \/\/ otherwise, tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"allocated an arena of \" << losFootprint << \" bytes for the unit LOS vectors\"\n << pyre::journal::endl;\n\n \/\/ compute the memory footprint for the dataset membership table\n const size_type oidFootprint = _nObservations * sizeof(size_type);\n \/\/ allocate device memory\n status = cudaMallocManaged(&_oids, oidFootprint);\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while allocating device memory for the dataset ids: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::bad_alloc();\n }\n \/\/ otherwise, tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"allocated an arena of \" << oidFootprint << \" bytes for the dataset ids\"\n << pyre::journal::endl;\n\n}\n\n\n\/\/ destructor\naltar::models::cudacdm::Source::\n~Source() {\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ sign on\n channel\n << pyre::journal::at(__HERE__)\n << \"deleting source \" << this\n << pyre::journal::endl;\n\n \/\/ deallocate device memory\n \/\/ if we were handed data\n if (_data) {\n \/\/ release it\n cudaFree(_data);\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \" released {_data} device memory at\" << _data\n << pyre::journal::endl;\n }\n\n \/\/ if we were handed the locations of the observation points\n if (_locations) {\n \/\/ release it\n cudaFree(_locations);\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \" released {_locations} device memory at\" << _locations\n << pyre::journal::endl;\n }\n\n \/\/ if we were handed line of sight vectors\n if (_los) {\n \/\/ release it\n cudaFree(_los);\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \" released {_los} device memory at\" << _los\n << pyre::journal::endl;\n\n }\n\n \/\/ if we were handed observation data set membership\n if (_oids) {\n \/\/ release it\n cudaFree(_oids);\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \" released {_oids} device memory at\" << _oids\n << pyre::journal::endl;\n }\n\n \/\/ if we were successful in allocating memory for the samples\n if (_samples) {\n \/\/ release it\n cudaFree(_samples);\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \" released {_samples} device memory at\" << _samples\n << pyre::journal::endl;\n }\n\n \/\/ if we were successful in allocating memory for the predicted displacements\n if (_predicted) {\n \/\/ release it\n cudaFree(_predicted);\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \" released {__predicted} device memory at\" << _predicted\n << pyre::journal::endl;\n }\n\n \/\/ all done\n channel\n << pyre::journal::at(__HERE__)\n << \"done deleting source \" << this\n << pyre::journal::endl;\n}\n\n\n\/\/ interface\nvoid\naltar::models::cudacdm::Source::\ndata(gsl_vector * data) {\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ compute the memory footprint\n const size_type dataFootprint = _nObservations * sizeof(data_type);\n \/\/ move the data from the vector to the device\n cudaError_t status = cudaMemcpy(_data, data->data, dataFootprint, cudaMemcpyHostToDevice);\n \/\/ check\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while copying data to the device: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::runtime_error(\"while copying data to the device\");\n }\n\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"attached data from \" << _data\n << pyre::journal::endl;\n\n \/\/ all done\n return;\n}\n\n\nvoid\naltar::models::cudacdm::Source::\nlocations(gsl_matrix * locations) {\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ we only have the (x,y) coordinates of the observation points on the surface\n const int dim = 2;\n \/\/ compute the number of locations\n const size_type nLoc = dim * _nObservations;\n \/\/ compute the memory footprint\n const size_type locationsFootprint = nLoc * sizeof(data_type);\n\n \/\/ we want to re-pack the coordinates; allocate a temporary buffer\n data_type * buffer = new data_type[nLoc];\n \/\/ go through the three axes\n for (size_type axis=0; axis < dim; ++axis) {\n \/\/ and the observations\n for (size_type obs=0; obs < _nObservations; ++obs) {\n \/\/ copy the data\n buffer[axis*_nObservations + obs] = gsl_matrix_get(locations, obs, axis);\n }\n }\n\n \/\/ move the data\n cudaError_t status = cudaMemcpy(_locations, buffer, locationsFootprint, cudaMemcpyHostToDevice);\n \/\/ clean up\n delete [] buffer;\n \/\/ check\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while copying location coordinates to the device: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::runtime_error(\"while copying location coordinates to the device\");\n }\n\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"attached locations from \" << _locations\n << pyre::journal::endl;\n\n \/\/ all done\n return;\n}\n\n\nvoid\naltar::models::cudacdm::Source::\nlos(gsl_matrix * los) {\n\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ we have the 3 components of the unit LOS vectors to the observation point on the ground\n const int dim = 3;\n \/\/ compute the number of components\n const size_type nLOS = dim * _nObservations;\n \/\/ compute the memory footprint\n const size_type losFootprint = nLOS * sizeof(data_type);\n\n \/\/ we want to re-pack the coordinates; allocate a temporary buffer\n data_type * buffer = new data_type[nLOS];\n \/\/ go through the three axes\n for (size_type axis=0; axis < dim; ++axis) {\n \/\/ and the observations\n for (size_type obs=0; obs < _nObservations; ++obs) {\n \/\/ copy the data\n buffer[axis*_nObservations + obs] = gsl_matrix_get(los, obs, axis);\n }\n }\n\n \/\/ move the data\n cudaError_t status = cudaMemcpy(_los, buffer, losFootprint, cudaMemcpyHostToDevice);\n \/\/ clean up\n delete [] buffer;\n \/\/ check\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while copying LOS components to the device: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::runtime_error(\"while copying LOS components to the device\");\n }\n\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"attached LOS matrix at \" << _los\n << pyre::journal::endl;\n\n \/\/ all done\n return;\n}\n\n\nvoid\naltar::models::cudacdm::Source::\noids(const oids_type & oids) {\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ compute the memory footprint\n const size_type oidFootprint = _nObservations * sizeof(size_type);\n \/\/ move the data\n cudaError_t status = cudaMemcpy(_oids, &oids[0], oidFootprint, cudaMemcpyHostToDevice);\n \/\/ check\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while copying dataset ids to the device: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::runtime_error(\"while copying dataset ids to the device\");\n }\n\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"attached data set ids to the observations\"\n << pyre::journal::endl;\n\n \/\/ all done\n return;\n}\n\n\nvoid\naltar::models::cudacdm::Source::\nresiduals(gsl_matrix_view * theta, gsl_matrix * residuals) const\n{\n\n \/\/ transfer the samples to the device\n _theta(theta);\n \/\/ compute the predicted displacements\n _displacements();\n \/\/ compute the residuals\n _residuals();\n \/\/ harvest the results\n _harvest(residuals);\n\n \/\/ all done\n return;\n}\n\n\n\/\/ implementation details\nvoid\naltar::models::cudacdm::Source::\n_theta(gsl_matrix_view * samples) const\n{\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ compute the total number of values in the sample set\n const size_type nValues = _nSamples * _nParameters;\n \/\/ the amount of memory they occupy\n const size_type valueFootprint = nValues * sizeof(data_type);\n \/\/ make a buffer to hold them\n data_type * values = new data_type[nValues];\n \/\/ go through the samples\n for (size_type sample=0; sample < _nSamples; ++sample) {\n \/\/ and all parameters\n for (size_type param=0; param < _nParameters; ++param) {\n \/\/ move the values over to the temporary buffer\n values[sample*_nParameters + param] = gsl_matrix_get(&samples->matrix, sample, param);\n }\n }\n \/\/ move to the device\n cudaError_t status = cudaMemcpy(_samples, values, valueFootprint, cudaMemcpyHostToDevice);\n \/\/ clean up the temporary buffer\n delete [] values;\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while copying samples to the device: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::runtime_error(\"while copying samples to the device\");\n }\n\n \/\/ tell me\n channel\n << pyre::journal::at(__HERE__)\n << \"transferred the samples to the device\"\n << pyre::journal::endl;\n\n \/\/ all done\n return;\n}\n\n\nvoid\naltar::models::cudacdm::Source::\n_harvest(gsl_matrix * residuals) const\n{\n \/\/ make a channel\n pyre::journal::debug_t channel(\"cudacdm.source\");\n\n \/\/ the number of cells in the results\n const size_type nCells = _nSamples * _nObservations;\n \/\/ the amount of memory they occupy\n const size_type dispFootprint = nCells * sizeof(data_type);\n \/\/ make some room for the results\n data_type * buffer = new data_type[nCells];\n \/\/ harvest the predicted displacements\n cudaError_t status = cudaMemcpy(buffer, _predicted, dispFootprint, cudaMemcpyDeviceToHost);\n \/\/ clean up\n delete [] buffer;\n \/\/ if something went wrong\n if (status != cudaSuccess) {\n \/\/ make a channel\n pyre::journal::error_t error(\"cudacdm.source\");\n \/\/ complain\n error\n << pyre::journal::at(__HERE__)\n << \"while harvesting residuals from the device: \"\n << cudaGetErrorName(status) << \" (\" << status << \")\"\n << pyre::journal::endl;\n \/\/ and bail\n throw std::runtime_error(\"while harvesting residuals\");\n }\n \/\/ go through the observation points\n for (size_type loc=0; loc < _nObservations; ++loc) {\n \/\/ and the samples\n for (size_type sample=0; sample < _nSamples; ++sample) {\n \/\/ transfer to the matrix\n gsl_matrix_set(residuals, sample, loc, buffer[loc*_nSamples + sample]);\n }\n }\n\n \/\/ all done\n return;\n}\n\n\n\/\/ end of file\n","avg_line_length":30.9792746114,"max_line_length":100,"alphanum_fraction":0.5953057925} {"size":115931,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"stag\/ED\/EDInternals.h\"\r\nnamespace stag {\r\n\r\n\/\/\/ Special defines\r\n#define EDGE_VERTICAL 1\r\n#define EDGE_HORIZONTAL 2\r\n#define EDGE_45 3\r\n#define EDGE_135 4\r\n\r\n#define TEMP_PIXEL 253\r\n#define ANCHOR_PIXEL 254\r\n#define EDGE_PIXEL 255\r\n\r\n\/\/#define LEFT 1\r\n\/\/#define RIGHT 2\r\n\/\/#define UP 3\r\n\/\/#define DOWN 4\r\n\r\n#define UP_LEFT 1 \/\/ diagonal\r\n#define UP 2\r\n#define UP_RIGHT 3\r\n#define RIGHT 4\r\n#define DOWN_RIGHT 5\r\n#define DOWN 6\r\n#define DOWN_LEFT 7\r\n#define LEFT 8\r\n\r\nstruct StackNode {\r\n int r, c; \/\/ starting pixel\r\n int parent; \/\/ parent chain (-1 if no parent)\r\n int dir; \/\/ direction where you are supposed to go\r\n};\r\n\r\n\/\/ Used during Edge Linking\r\nstruct Chain {\r\n short dir; \/\/ Direction of the chain\r\n unsigned short len; \/\/ # of pixels in the chain\r\n short parent; \/\/ Parent of this node (-1 if no parent)\r\n short children[2]; \/\/ Children of this node (-1 if no children)\r\n Pixel *pixels; \/\/ Pointer to the beginning of the pixels array\r\n};\r\n\r\n\/\/\/-----------------------------------------------------------------------------------\r\n\/\/\/ Compute anchor points\r\n\/\/\/\r\nstatic void ComputeAnchorPoints(short *gradImg, unsigned char *dirImg,\r\n EdgeMap *map, int GRADIENT_THRESH,\r\n int ANCHOR_THRESH, int SCAN_INTERVAL) {\r\n int width = map->width;\r\n int height = map->height;\r\n\r\n unsigned char *edgeImg = map->edgeImg;\r\n memset(edgeImg, 0, width * height);\r\n\r\n for (int i = 2; i < height - 2; i++) {\r\n int start = 2;\r\n int inc = 1;\r\n if (i % SCAN_INTERVAL != 0) {\r\n start = SCAN_INTERVAL;\r\n inc = SCAN_INTERVAL;\r\n }\r\n\r\n for (int j = start; j < width - 2; j += inc) {\r\n if (gradImg[i * width + j] < GRADIENT_THRESH) continue;\r\n\r\n if (dirImg[i * width + j] == EDGE_VERTICAL) {\r\n \/\/ vertical edge\r\n int diff1 = gradImg[i * width + j] - gradImg[i * width + j - 1];\r\n int diff2 = gradImg[i * width + j] - gradImg[i * width + j + 1];\r\n if (diff1 >= ANCHOR_THRESH && diff2 >= ANCHOR_THRESH)\r\n edgeImg[i * width + j] = ANCHOR_PIXEL;\r\n\r\n } else {\r\n \/\/ horizontal edge\r\n int diff1 = gradImg[i * width + j] - gradImg[(i - 1) * width + j];\r\n int diff2 = gradImg[i * width + j] - gradImg[(i + 1) * width + j];\r\n if (diff1 >= ANCHOR_THRESH && diff2 >= ANCHOR_THRESH)\r\n edgeImg[i * width + j] = ANCHOR_PIXEL;\r\n } \/\/ end-else\r\n } \/\/ end-for-inner\r\n } \/\/ end-for-outer\r\n} \/\/ end-ComputeAnchorPoints\r\n\r\n\/\/\/-----------------------------------------------------------------------------------\r\n\/\/\/ Compute anchor points using 4 directions (0, 45, 90 and 135 degree edges)\r\n\/\/\/\r\n\/\/ static void ComputeAnchorPoints4Dirs(short *gradImg, unsigned char *dirImg,\r\n\/\/ EdgeMap *map, int GRADIENT_THRESH,\r\n\/\/ int ANCHOR_THRESH, int SCAN_INTERVAL) {\r\n\/\/ int width = map->width;\r\n\/\/ int height = map->height;\r\n\r\n\/\/ unsigned char *edgeImg = map->edgeImg;\r\n\/\/ memset(edgeImg, 0, width * height);\r\n\r\n\/\/ for (int i = 2; i < height - 2; i++) {\r\n\/\/ int start = 2;\r\n\/\/ int inc = 1;\r\n\/\/ if (i % SCAN_INTERVAL != 0) {\r\n\/\/ start = SCAN_INTERVAL;\r\n\/\/ inc = SCAN_INTERVAL;\r\n\/\/ }\r\n\r\n\/\/ for (int j = start; j < width - 2; j += inc) {\r\n\/\/ if (gradImg[i * width + j] < GRADIENT_THRESH) continue;\r\n\r\n\/\/ if (dirImg[i * width + j] == EDGE_VERTICAL) {\r\n\/\/ \/\/ vertical edge\r\n\/\/ int diff1 = gradImg[i * width + j] - gradImg[i * width + j - 1];\r\n\/\/ int diff2 = gradImg[i * width + j] - gradImg[i * width + j + 1];\r\n\/\/ if (diff1 >= ANCHOR_THRESH && diff2 >= ANCHOR_THRESH)\r\n\/\/ edgeImg[i * width + j] = ANCHOR_PIXEL;\r\n\r\n\/\/ } else if (dirImg[i * width + j] == EDGE_HORIZONTAL) {\r\n\/\/ \/\/ horizontal edge\r\n\/\/ int diff1 = gradImg[i * width + j] - gradImg[(i - 1) * width + j];\r\n\/\/ int diff2 = gradImg[i * width + j] - gradImg[(i + 1) * width + j];\r\n\/\/ if (diff1 >= ANCHOR_THRESH && diff2 >= ANCHOR_THRESH)\r\n\/\/ edgeImg[i * width + j] = ANCHOR_PIXEL;\r\n\r\n\/\/ } else if (dirImg[i * width + j] == EDGE_45) {\r\n\/\/ \/\/ 45 degree edge\r\n\/\/ int diff1 = gradImg[i * width + j] - gradImg[(i - 1) * width + j - 1];\r\n\/\/ int diff2 = gradImg[i * width + j] - gradImg[(i + 1) * width + j + 1];\r\n\/\/ if (diff1 >= ANCHOR_THRESH && diff2 >= ANCHOR_THRESH)\r\n\/\/ edgeImg[i * width + j] = ANCHOR_PIXEL;\r\n\r\n\/\/ } else { \/\/ if (dirImg[i*width+j] == EDGE_135){\r\n\/\/ \/\/ 45 degree edge\r\n\/\/ int diff1 = gradImg[i * width + j] - gradImg[(i - 1) * width + j + 1];\r\n\/\/ int diff2 = gradImg[i * width + j] - gradImg[(i + 1) * width + j - 1];\r\n\/\/ if (diff1 >= ANCHOR_THRESH && diff2 >= ANCHOR_THRESH)\r\n\/\/ edgeImg[i * width + j] = ANCHOR_PIXEL;\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-for-inner\r\n\/\/ } \/\/ end-for-outer\r\n\/\/ } \/\/ end-ComputeAnchorPoints4Dirs\r\n\r\n\/\/\/--------------------------------------------------------------------------\r\n\/\/\/ Computes anchor offsets & sorts them\r\n\/\/\/\r\nstatic int *SortAnchorsByGradValue(short *gradImg, EdgeMap *map,\r\n int *pNoAnchors) {\r\n int width = map->width;\r\n int height = map->height;\r\n\r\n int SIZE = 128 * 256;\r\n int *C = new int[SIZE];\r\n memset(C, 0, sizeof(int) * SIZE);\r\n\r\n \/\/ Count the number of grad values\r\n for (int i = 1; i < height - 1; i++) {\r\n for (int j = 1; j < width - 1; j++) {\r\n if (map->edgeImg[i * width + j] != ANCHOR_PIXEL) continue;\r\n\r\n int grad = gradImg[i * width + j];\r\n C[grad]++;\r\n } \/\/ end-for\r\n } \/\/ end-for\r\n\r\n \/\/ Compute indices\r\n for (int i = 1; i < SIZE; i++) C[i] += C[i - 1];\r\n\r\n int noAnchors = C[SIZE - 1];\r\n int *A = new int[noAnchors];\r\n memset(A, 0, sizeof(int) * noAnchors);\r\n\r\n for (int i = 1; i < height - 1; i++) {\r\n for (int j = 1; j < width - 1; j++) {\r\n if (map->edgeImg[i * width + j] != ANCHOR_PIXEL) continue;\r\n\r\n int grad = gradImg[i * width + j];\r\n int index = --C[grad];\r\n A[index] = i * width + j; \/\/ anchor's offset\r\n } \/\/ end-for\r\n } \/\/ end-for\r\n\r\n delete C;\r\n\r\n *pNoAnchors = noAnchors;\r\n return A;\r\n} \/\/ end-SortAnchorsByGradValue\r\n\r\n\/\/\/--------------------------------------------------------------------------\r\n\/\/\/ Computes the length of the longest chain\r\n\/\/\/\r\nstatic int LongestChain(Chain *chains, int root) {\r\n if (root == -1 || chains[root].len == 0) return 0;\r\n\r\n int len0 = 0;\r\n if (chains[root].children[0] != -1)\r\n len0 = LongestChain(chains, chains[root].children[0]);\r\n\r\n int len1 = 0;\r\n if (chains[root].children[1] != -1)\r\n len1 = LongestChain(chains, chains[root].children[1]);\r\n\r\n int max = 0;\r\n\r\n if (len0 >= len1) {\r\n max = len0;\r\n chains[root].children[1] = -1;\r\n\r\n } else {\r\n max = len1;\r\n chains[root].children[0] = -1;\r\n } \/\/ end-else\r\n\r\n return chains[root].len + max;\r\n} \/\/ end-LongestChain\r\n\r\n\/\/\/-----------------------------------------------------------\r\n\/\/\/ Retrieves the chain nos from the tree\r\n\/\/\/\r\nstatic int RetrieveChainNos(Chain *chains, int root, int chainNos[]) {\r\n int count = 0;\r\n\r\n while (root != -1) {\r\n chainNos[count] = root;\r\n count++;\r\n\r\n if (chains[root].children[0] != -1)\r\n root = chains[root].children[0];\r\n else\r\n root = chains[root].children[1];\r\n } \/\/ end-while\r\n\r\n return count;\r\n} \/\/ end-RetrieveChainNos\r\n\r\n\/\/\/-----------------------------------------------------------------------------------\r\n\/\/\/ Join anchor points and compute segment chains at the same time\r\n\/\/\/\r\n\/\/ static void JoinAnchorPoints(short *gradImg, unsigned char *dirImg,\r\n\/\/ EdgeMap *map, int GRADIENT_THRESH,\r\n\/\/ int MIN_PATH_LEN) {\r\n\/\/ int width = map->width;\r\n\/\/ int height = map->height;\r\n\r\n\/\/ unsigned char *edgeImg = map->edgeImg;\r\n\/\/ int *chainNos = new int[(width + height) * 8];\r\n\r\n\/\/ Pixel *pixels = new Pixel[width * height];\r\n\/\/ StackNode *stack = new StackNode[width * height];\r\n\/\/ Chain *chains = new Chain[width * height];\r\n\r\n\/\/ int noSegments = 0;\r\n\/\/ int totalPixels = 0;\r\n\r\n\/\/ for (int i = 2; i < height - 2; i++) {\r\n\/\/ for (int j = 2; j < width - 2; j++) {\r\n\/\/ if (edgeImg[i * width + j] != ANCHOR_PIXEL) continue;\r\n\r\n\/\/ chains[0].len = 0;\r\n\/\/ chains[0].parent = -1;\r\n\/\/ chains[0].dir = 0;\r\n\/\/ chains[0].children[0] = chains[0].children[1] = -1;\r\n\/\/ chains[0].pixels = NULL;\r\n\r\n\/\/ int noChains = 1;\r\n\/\/ int len = 0;\r\n\/\/ int duplicatePixelCount = 0;\r\n\r\n\/\/ int top = -1; \/\/ top of the stack\r\n\r\n\/\/ if (dirImg[i * width + j] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ } else {\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = 0;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ \/\/ While the stack is not empty\r\n\/\/ StartOfWhile:\r\n\/\/ while (top >= 0) {\r\n\/\/ int r = stack[top].r;\r\n\/\/ int c = stack[top].c;\r\n\/\/ int dir = stack[top].dir;\r\n\/\/ int parent = stack[top].parent;\r\n\/\/ top--;\r\n\r\n\/\/ if (edgeImg[r * width + c] != EDGE_PIXEL) duplicatePixelCount++;\r\n\r\n\/\/ chains[noChains].dir = dir; \/\/ traversal direction\r\n\/\/ chains[noChains].parent = parent;\r\n\/\/ chains[noChains].children[0] = chains[noChains].children[1] = -1;\r\n\r\n\/\/ int chainLen = 0;\r\n\/\/ chains[noChains].pixels = &pixels[len];\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\r\n\/\/ if (dir == LEFT) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is horizontal. Look LEFT\r\n\/\/ \/\/\r\n\/\/ \/\/ A\r\n\/\/ \/\/ B x\r\n\/\/ \/\/ C\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup up & down pixels\r\n\/\/ if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[r * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow max. pixel to the LEFT\r\n\/\/ int A = gradImg[(r - 1) * width + c - 1];\r\n\/\/ int B = gradImg[r * width + c - 1];\r\n\/\/ int C = gradImg[(r + 1) * width + c - 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ r--;\r\n\/\/ else\r\n\/\/ r++;\r\n\/\/ } else if (C > B)\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == RIGHT) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is horizontal. Look RIGHT\r\n\/\/ \/\/\r\n\/\/ \/\/ A\r\n\/\/ \/\/ x B\r\n\/\/ \/\/ C\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup up&down pixels\r\n\/\/ if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c] = 0;\r\n\/\/ if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[r * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c++;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow max. pixel to the RIGHT\r\n\/\/ int A = gradImg[(r - 1) * width + c + 1];\r\n\/\/ int B = gradImg[r * width + c + 1];\r\n\/\/ int C = gradImg[(r + 1) * width + c + 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ r--; \/\/ A\r\n\/\/ else\r\n\/\/ r++; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ r++; \/\/ C\r\n\/\/ c++;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN; \/\/ Go down\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP; \/\/ Go up\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == UP) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is vertical. Look UP\r\n\/\/ \/\/\r\n\/\/ \/\/ A B C\r\n\/\/ \/\/ x\r\n\/\/ \/\/\r\n\/\/ \/\/ Cleanup left & right pixels\r\n\/\/ if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c - 1] = 0;\r\n\/\/ if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c + 1] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r - 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c++;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel UP\r\n\/\/ int A = gradImg[(r - 1) * width + c - 1];\r\n\/\/ int B = gradImg[(r - 1) * width + c];\r\n\/\/ int C = gradImg[(r - 1) * width + c + 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c--;\r\n\/\/ else\r\n\/\/ c++;\r\n\/\/ } else if (C > B)\r\n\/\/ c++;\r\n\/\/ r--;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else { \/\/ dir == DOWN\r\n\/\/ while (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is vertical\r\n\/\/ \/\/\r\n\/\/ \/\/ x\r\n\/\/ \/\/ A B C\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup side pixels\r\n\/\/ if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c + 1] = 0;\r\n\/\/ if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c - 1] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r + 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel DOWN\r\n\/\/ int A = gradImg[(r + 1) * width + c - 1];\r\n\/\/ int B = gradImg[(r + 1) * width + c];\r\n\/\/ int C = gradImg[(r + 1) * width + c + 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c--; \/\/ A\r\n\/\/ else\r\n\/\/ c++; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ c++; \/\/ C\r\n\/\/ r++;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (len - duplicatePixelCount < MIN_PATH_LEN) {\r\n\/\/ for (int k = 0; k < len; k++) {\r\n\/\/ edgeImg[pixels[k].r * width + pixels[k].c] = 0;\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ } else {\r\n\/\/ map->segments[noSegments].pixels = &map->pixels[totalPixels];\r\n\r\n\/\/ int totalLen = LongestChain(chains, chains[0].children[1]);\r\n\/\/ int noSegmentPixels = 0;\r\n\r\n\/\/ if (totalLen > 0) {\r\n\/\/ \/\/ Retrieve the chainNos\r\n\/\/ int count = RetrieveChainNos(chains, chains[0].children[1], chainNos);\r\n\r\n\/\/ \/\/ Copy these pixels in the reverse order\r\n\/\/ for (int k = count - 1; k >= 0; k--) {\r\n\/\/ int chainNo = chainNos[k];\r\n\r\n\/\/ #if 1\r\n\/\/ \/* See if we can erase some pixels from the last chain. This is for\r\n\/\/ * cleanup *\/\r\n\/\/ int fr = chains[chainNo].pixels[chains[chainNo].len - 1].r;\r\n\/\/ int fc = chains[chainNo].pixels[chains[chainNo].len - 1].c;\r\n\r\n\/\/ int index = noSegmentPixels - 2;\r\n\/\/ while (index >= 0) {\r\n\/\/ int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n\/\/ int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ \/\/ neighbors. Erase last pixel\r\n\/\/ noSegmentPixels--;\r\n\/\/ index--;\r\n\/\/ } else\r\n\/\/ break;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (chains[chainNo].len > 1) {\r\n\/\/ fr = chains[chainNo].pixels[chains[chainNo].len - 2].r;\r\n\/\/ fc = chains[chainNo].pixels[chains[chainNo].len - 2].c;\r\n\r\n\/\/ int dr = abs(\r\n\/\/ fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc = abs(\r\n\/\/ fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) chains[chainNo].len--;\r\n\/\/ } \/\/ end-if\r\n\/\/ #endif\r\n\r\n\/\/ for (int l = chains[chainNo].len - 1; l >= 0; l--) {\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels++] =\r\n\/\/ chains[chainNo].pixels[l];\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ chains[chainNo].len = 0; \/\/ Mark as copied\r\n\/\/ } \/\/ end-for\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ totalLen = LongestChain(chains, chains[0].children[0]);\r\n\/\/ if (totalLen > 1) {\r\n\/\/ \/\/ Retrieve the chainNos\r\n\/\/ int count = RetrieveChainNos(chains, chains[0].children[0], chainNos);\r\n\r\n\/\/ \/\/ Copy these chains in the forward direction. Skip the first pixel of\r\n\/\/ \/\/ the first chain due to repetition with the last pixel of the\r\n\/\/ \/\/ previous chain\r\n\/\/ int lastChainNo = chainNos[0];\r\n\/\/ chains[lastChainNo].pixels++;\r\n\/\/ chains[lastChainNo].len--;\r\n\r\n\/\/ for (int k = 0; k < count; k++) {\r\n\/\/ int chainNo = chainNos[k];\r\n\r\n\/\/ #if 1\r\n\/\/ \/* See if we can erase some pixels from the last chain. This is for\r\n\/\/ * cleanup *\/\r\n\/\/ int fr = chains[chainNo].pixels[0].r;\r\n\/\/ int fc = chains[chainNo].pixels[0].c;\r\n\r\n\/\/ int index = noSegmentPixels - 2;\r\n\/\/ while (index >= 0) {\r\n\/\/ int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n\/\/ int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ \/\/ neighbors. Erase last pixel\r\n\/\/ noSegmentPixels--;\r\n\/\/ index--;\r\n\/\/ } else\r\n\/\/ break;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ int startIndex = 0;\r\n\/\/ int chainLen = chains[chainNo].len;\r\n\/\/ if (chainLen > 1) {\r\n\/\/ int fr = chains[chainNo].pixels[1].r;\r\n\/\/ int fc = chains[chainNo].pixels[1].c;\r\n\r\n\/\/ int dr = abs(\r\n\/\/ fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc = abs(\r\n\/\/ fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ startIndex = 1;\r\n\/\/ }\r\n\/\/ } \/\/ end-if\r\n\/\/ #endif\r\n\r\n\/\/ \/* Start a new chain & copy pixels from the new chain *\/\r\n\/\/ for (int l = startIndex; l < chains[chainNo].len; l++) {\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels++] =\r\n\/\/ chains[chainNo].pixels[l];\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ chains[chainNo].len = 0; \/\/ Mark as copied\r\n\/\/ } \/\/ end-for\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ map->segments[noSegments].noPixels = noSegmentPixels;\r\n\/\/ totalPixels += noSegmentPixels;\r\n\r\n\/\/ \/\/ See if the first pixel can be cleaned up\r\n\/\/ int fr = map->segments[noSegments].pixels[1].r;\r\n\/\/ int fc = map->segments[noSegments].pixels[1].c;\r\n\r\n\/\/ int dr =\r\n\/\/ abs(fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc =\r\n\/\/ abs(fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ map->segments[noSegments].pixels++;\r\n\/\/ map->segments[noSegments].noPixels--;\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ noSegments++;\r\n\r\n\/\/ \/\/ Copy the rest of the long chains here\r\n\/\/ for (int k = 2; k < noChains; k++) {\r\n\/\/ if (chains[k].len < 2) continue;\r\n\r\n\/\/ totalLen = LongestChain(chains, k);\r\n\r\n\/\/ \/\/ If long enough, copy\r\n\/\/ if (totalLen >= 10) {\r\n\/\/ map->segments[noSegments].pixels = &map->pixels[totalPixels];\r\n\r\n\/\/ \/\/ Retrieve the chainNos\r\n\/\/ int count = RetrieveChainNos(chains, k, chainNos);\r\n\r\n\/\/ \/\/ Copy the pixels\r\n\/\/ noSegmentPixels = 0;\r\n\/\/ for (int k = 0; k < count; k++) {\r\n\/\/ int chainNo = chainNos[k];\r\n\r\n\/\/ #if 1\r\n\/\/ \/* See if we can erase some pixels from the last chain. This is\r\n\/\/ * for cleanup *\/\r\n\/\/ int fr = chains[chainNo].pixels[0].r;\r\n\/\/ int fc = chains[chainNo].pixels[0].c;\r\n\r\n\/\/ int index = noSegmentPixels - 2;\r\n\/\/ while (index >= 0) {\r\n\/\/ int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n\/\/ int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ \/\/ neighbors. Erase last pixel\r\n\/\/ noSegmentPixels--;\r\n\/\/ index--;\r\n\/\/ } else\r\n\/\/ break;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ int startIndex = 0;\r\n\/\/ int chainLen = chains[chainNo].len;\r\n\/\/ if (chainLen > 1) {\r\n\/\/ int fr = chains[chainNo].pixels[1].r;\r\n\/\/ int fc = chains[chainNo].pixels[1].c;\r\n\r\n\/\/ int dr = abs(\r\n\/\/ fr -\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc = abs(\r\n\/\/ fc -\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ startIndex = 1;\r\n\/\/ }\r\n\/\/ } \/\/ end-if\r\n\/\/ #endif\r\n\/\/ \/* Start a new chain & copy pixels from the new chain *\/\r\n\/\/ for (int l = startIndex; l < chains[chainNo].len; l++) {\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels++] =\r\n\/\/ chains[chainNo].pixels[l];\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ chains[chainNo].len = 0; \/\/ Mark as copied\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ map->segments[noSegments].noPixels = noSegmentPixels;\r\n\/\/ totalPixels += noSegmentPixels;\r\n\r\n\/\/ noSegments++;\r\n\/\/ } \/\/ end-if\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ } \/\/ end-for-inner\r\n\/\/ } \/\/ end-for-outer\r\n\r\n\/\/ map->noSegments = noSegments;\r\n\r\n\/\/ delete chains;\r\n\/\/ delete stack;\r\n\/\/ delete pixels;\r\n\/\/ delete chainNos;\r\n\/\/ } \/\/ end-JoinAnchorPoints\r\n\r\n\/\/\/-----------------------------------------------------------------------------------\r\n\/\/\/ Join anchors starting with the anchor having the maximum gradient value.\r\n\/\/\/ To do this, we need to first sort the anchors\r\n\/\/\/\r\n\/\/\/ static\r\nvoid JoinAnchorPointsUsingSortedAnchors(short *gradImg, unsigned char *dirImg,\r\n EdgeMap *map, int GRADIENT_THRESH,\r\n int MIN_PATH_LEN) {\r\n int width = map->width;\r\n int height = map->height;\r\n\r\n unsigned char *edgeImg = map->edgeImg;\r\n int *chainNos = new int[(width + height) * 8];\r\n\r\n Pixel *pixels = new Pixel[width * height];\r\n StackNode *stack = new StackNode[width * height];\r\n Chain *chains = new Chain[width * height];\r\n\r\n \/\/ First Sort the anchors\r\n int noAnchors;\r\n int *A = SortAnchorsByGradValue(gradImg, map, &noAnchors);\r\n\r\n \/\/ Now join the anchors starting with the anchor having the greatest gradient\r\n \/\/ value\r\n int noSegments = 0;\r\n int totalPixels = 0;\r\n\r\n for (int k = noAnchors - 1; k >= 0; k--) {\r\n int pixelOffset = A[k];\r\n\r\n int i = pixelOffset \/ width;\r\n int j = pixelOffset % width;\r\n\r\n if (edgeImg[i * width + j] != ANCHOR_PIXEL) continue;\r\n\r\n chains[0].len = 0;\r\n chains[0].parent = -1;\r\n chains[0].dir = 0;\r\n chains[0].children[0] = chains[0].children[1] = -1;\r\n chains[0].pixels = NULL;\r\n\r\n int noChains = 1;\r\n int len = 0;\r\n int duplicatePixelCount = 0;\r\n\r\n int top = -1; \/\/ top of the stack\r\n\r\n if (dirImg[i * width + j] == EDGE_VERTICAL) {\r\n stack[++top].r = i;\r\n stack[top].c = j;\r\n stack[top].dir = DOWN;\r\n stack[top].parent = 0;\r\n\r\n stack[++top].r = i;\r\n stack[top].c = j;\r\n stack[top].dir = UP;\r\n stack[top].parent = 0;\r\n\r\n } else {\r\n stack[++top].r = i;\r\n stack[top].c = j;\r\n stack[top].dir = RIGHT;\r\n stack[top].parent = 0;\r\n\r\n stack[++top].r = i;\r\n stack[top].c = j;\r\n stack[top].dir = LEFT;\r\n stack[top].parent = 0;\r\n } \/\/ end-else\r\n\r\n \/\/ While the stack is not empty\r\n StartOfWhile:\r\n while (top >= 0) {\r\n int r = stack[top].r;\r\n int c = stack[top].c;\r\n int dir = stack[top].dir;\r\n int parent = stack[top].parent;\r\n top--;\r\n\r\n if (edgeImg[r * width + c] != EDGE_PIXEL) duplicatePixelCount++;\r\n\r\n chains[noChains].dir = dir; \/\/ traversal direction\r\n chains[noChains].parent = parent;\r\n chains[noChains].children[0] = chains[noChains].children[1] = -1;\r\n\r\n int chainLen = 0;\r\n chains[noChains].pixels = &pixels[len];\r\n\r\n pixels[len].r = r;\r\n pixels[len].c = c;\r\n len++;\r\n chainLen++;\r\n\r\n if (dir == LEFT) {\r\n while (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n \/\/ The edge is horizontal. Look LEFT\r\n \/\/\r\n \/\/ A\r\n \/\/ B x\r\n \/\/ C\r\n \/\/\r\n \/\/ cleanup up & down pixels\r\n if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n edgeImg[(r - 1) * width + c] = 0;\r\n if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n edgeImg[(r + 1) * width + c] = 0;\r\n\r\n \/\/ Look if there is an edge pixel in the neighbors\r\n if (edgeImg[r * width + c - 1] >= ANCHOR_PIXEL) {\r\n c--;\r\n } else if (edgeImg[(r - 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n r--;\r\n c--;\r\n } else if (edgeImg[(r + 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n r++;\r\n c--;\r\n } else {\r\n \/\/ else -- follow max. pixel to the LEFT\r\n int A = gradImg[(r - 1) * width + c - 1];\r\n int B = gradImg[r * width + c - 1];\r\n int C = gradImg[(r + 1) * width + c - 1];\r\n\r\n if (A > B) {\r\n if (A > C)\r\n r--;\r\n else\r\n r++;\r\n } else if (C > B)\r\n r++;\r\n c--;\r\n } \/\/ end-else\r\n\r\n if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n gradImg[r * width + c] < GRADIENT_THRESH) {\r\n if (chainLen > 0) {\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[0] = noChains;\r\n noChains++;\r\n } \/\/ end-if\r\n goto StartOfWhile;\r\n } \/\/ end-else\r\n\r\n pixels[len].r = r;\r\n pixels[len].c = c;\r\n len++;\r\n chainLen++;\r\n } \/\/ end-while\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = DOWN;\r\n stack[top].parent = noChains;\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = UP;\r\n stack[top].parent = noChains;\r\n\r\n len--;\r\n chainLen--;\r\n\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[0] = noChains;\r\n noChains++;\r\n\r\n } else if (dir == RIGHT) {\r\n while (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n \/\/ The edge is horizontal. Look RIGHT\r\n \/\/\r\n \/\/ A\r\n \/\/ x B\r\n \/\/ C\r\n \/\/\r\n \/\/ cleanup up&down pixels\r\n if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n edgeImg[(r + 1) * width + c] = 0;\r\n if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n edgeImg[(r - 1) * width + c] = 0;\r\n\r\n \/\/ Look if there is an edge pixel in the neighbors\r\n if (edgeImg[r * width + c + 1] >= ANCHOR_PIXEL) {\r\n c++;\r\n } else if (edgeImg[(r + 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n r++;\r\n c++;\r\n } else if (edgeImg[(r - 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n r--;\r\n c++;\r\n } else {\r\n \/\/ else -- follow max. pixel to the RIGHT\r\n int A = gradImg[(r - 1) * width + c + 1];\r\n int B = gradImg[r * width + c + 1];\r\n int C = gradImg[(r + 1) * width + c + 1];\r\n\r\n if (A > B) {\r\n if (A > C)\r\n r--; \/\/ A\r\n else\r\n r++; \/\/ C\r\n } else if (C > B)\r\n r++; \/\/ C\r\n c++;\r\n } \/\/ end-else\r\n\r\n if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n gradImg[r * width + c] < GRADIENT_THRESH) {\r\n if (chainLen > 0) {\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[1] = noChains;\r\n noChains++;\r\n } \/\/ end-if\r\n goto StartOfWhile;\r\n } \/\/ end-else\r\n\r\n pixels[len].r = r;\r\n pixels[len].c = c;\r\n len++;\r\n chainLen++;\r\n } \/\/ end-while\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = DOWN; \/\/ Go down\r\n stack[top].parent = noChains;\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = UP; \/\/ Go up\r\n stack[top].parent = noChains;\r\n\r\n len--;\r\n chainLen--;\r\n\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[1] = noChains;\r\n noChains++;\r\n\r\n } else if (dir == UP) {\r\n while (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n \/\/ The edge is vertical. Look UP\r\n \/\/\r\n \/\/ A B C\r\n \/\/ x\r\n \/\/\r\n \/\/ Cleanup left & right pixels\r\n if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n edgeImg[r * width + c - 1] = 0;\r\n if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n edgeImg[r * width + c + 1] = 0;\r\n\r\n \/\/ Look if there is an edge pixel in the neighbors\r\n if (edgeImg[(r - 1) * width + c] >= ANCHOR_PIXEL) {\r\n r--;\r\n } else if (edgeImg[(r - 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n r--;\r\n c--;\r\n } else if (edgeImg[(r - 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n r--;\r\n c++;\r\n } else {\r\n \/\/ else -- follow the max. pixel UP\r\n int A = gradImg[(r - 1) * width + c - 1];\r\n int B = gradImg[(r - 1) * width + c];\r\n int C = gradImg[(r - 1) * width + c + 1];\r\n\r\n if (A > B) {\r\n if (A > C)\r\n c--;\r\n else\r\n c++;\r\n } else if (C > B)\r\n c++;\r\n r--;\r\n } \/\/ end-else\r\n\r\n if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n gradImg[r * width + c] < GRADIENT_THRESH) {\r\n if (chainLen > 0) {\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[0] = noChains;\r\n noChains++;\r\n } \/\/ end-if\r\n goto StartOfWhile;\r\n } \/\/ end-else\r\n\r\n pixels[len].r = r;\r\n pixels[len].c = c;\r\n len++;\r\n chainLen++;\r\n } \/\/ end-while\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = RIGHT;\r\n stack[top].parent = noChains;\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = LEFT;\r\n stack[top].parent = noChains;\r\n\r\n len--;\r\n chainLen--;\r\n\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[0] = noChains;\r\n noChains++;\r\n\r\n } else { \/\/ dir == DOWN\r\n while (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n \/\/ The edge is vertical\r\n \/\/\r\n \/\/ x\r\n \/\/ A B C\r\n \/\/\r\n \/\/ cleanup side pixels\r\n if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n edgeImg[r * width + c + 1] = 0;\r\n if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n edgeImg[r * width + c - 1] = 0;\r\n\r\n \/\/ Look if there is an edge pixel in the neighbors\r\n if (edgeImg[(r + 1) * width + c] >= ANCHOR_PIXEL) {\r\n r++;\r\n } else if (edgeImg[(r + 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n r++;\r\n c++;\r\n } else if (edgeImg[(r + 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n r++;\r\n c--;\r\n } else {\r\n \/\/ else -- follow the max. pixel DOWN\r\n int A = gradImg[(r + 1) * width + c - 1];\r\n int B = gradImg[(r + 1) * width + c];\r\n int C = gradImg[(r + 1) * width + c + 1];\r\n\r\n if (A > B) {\r\n if (A > C)\r\n c--; \/\/ A\r\n else\r\n c++; \/\/ C\r\n } else if (C > B)\r\n c++; \/\/ C\r\n r++;\r\n } \/\/ end-else\r\n\r\n if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n gradImg[r * width + c] < GRADIENT_THRESH) {\r\n if (chainLen > 0) {\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[1] = noChains;\r\n noChains++;\r\n } \/\/ end-if\r\n goto StartOfWhile;\r\n } \/\/ end-else\r\n\r\n pixels[len].r = r;\r\n pixels[len].c = c;\r\n len++;\r\n chainLen++;\r\n } \/\/ end-while\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = RIGHT;\r\n stack[top].parent = noChains;\r\n\r\n stack[++top].r = r;\r\n stack[top].c = c;\r\n stack[top].dir = LEFT;\r\n stack[top].parent = noChains;\r\n\r\n len--;\r\n chainLen--;\r\n\r\n chains[noChains].len = chainLen;\r\n chains[parent].children[1] = noChains;\r\n noChains++;\r\n } \/\/ end-else\r\n\r\n } \/\/ end-while\r\n\r\n if (len - duplicatePixelCount < MIN_PATH_LEN) {\r\n for (int k = 0; k < len; k++) {\r\n edgeImg[pixels[k].r * width + pixels[k].c] = 0;\r\n } \/\/ end-for\r\n\r\n } else {\r\n map->segments[noSegments].pixels = &map->pixels[totalPixels];\r\n\r\n int totalLen = LongestChain(chains, chains[0].children[1]);\r\n int noSegmentPixels = 0;\r\n\r\n if (totalLen > 0) {\r\n \/\/ Retrieve the chainNos\r\n int count = RetrieveChainNos(chains, chains[0].children[1], chainNos);\r\n\r\n \/\/ Copy these pixels in the reverse order\r\n for (int k = count - 1; k >= 0; k--) {\r\n int chainNo = chainNos[k];\r\n\r\n#if 1\r\n \/* See if we can erase some pixels from the last chain. This is for\r\n * cleanup *\/\r\n int fr = chains[chainNo].pixels[chains[chainNo].len - 1].r;\r\n int fc = chains[chainNo].pixels[chains[chainNo].len - 1].c;\r\n\r\n int index = noSegmentPixels - 2;\r\n while (index >= 0) {\r\n int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n if (dr <= 1 && dc <= 1) {\r\n \/\/ neighbors. Erase last pixel\r\n noSegmentPixels--;\r\n index--;\r\n } else\r\n break;\r\n } \/\/ end-while\r\n\r\n if (chains[chainNo].len > 1) {\r\n fr = chains[chainNo].pixels[chains[chainNo].len - 2].r;\r\n fc = chains[chainNo].pixels[chains[chainNo].len - 2].c;\r\n\r\n int dr = abs(\r\n fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n int dc = abs(\r\n fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n if (dr <= 1 && dc <= 1) chains[chainNo].len--;\r\n } \/\/ end-if\r\n#endif\r\n\r\n for (int l = chains[chainNo].len - 1; l >= 0; l--) {\r\n map->segments[noSegments].pixels[noSegmentPixels++] =\r\n chains[chainNo].pixels[l];\r\n } \/\/ end-for\r\n\r\n chains[chainNo].len = 0; \/\/ Mark as copied\r\n } \/\/ end-for\r\n } \/\/ end-if\r\n\r\n totalLen = LongestChain(chains, chains[0].children[0]);\r\n if (totalLen > 1) {\r\n \/\/ Retrieve the chainNos\r\n int count = RetrieveChainNos(chains, chains[0].children[0], chainNos);\r\n\r\n \/\/ Copy these chains in the forward direction. Skip the first pixel of\r\n \/\/ the first chain due to repetition with the last pixel of the previous\r\n \/\/ chain\r\n int lastChainNo = chainNos[0];\r\n chains[lastChainNo].pixels++;\r\n chains[lastChainNo].len--;\r\n\r\n for (int k = 0; k < count; k++) {\r\n int chainNo = chainNos[k];\r\n\r\n#if 1\r\n \/* See if we can erase some pixels from the last chain. This is for\r\n * cleanup *\/\r\n int fr = chains[chainNo].pixels[0].r;\r\n int fc = chains[chainNo].pixels[0].c;\r\n\r\n int index = noSegmentPixels - 2;\r\n while (index >= 0) {\r\n int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n if (dr <= 1 && dc <= 1) {\r\n \/\/ neighbors. Erase last pixel\r\n noSegmentPixels--;\r\n index--;\r\n } else\r\n break;\r\n } \/\/ end-while\r\n\r\n int startIndex = 0;\r\n int chainLen = chains[chainNo].len;\r\n if (chainLen > 1) {\r\n int fr = chains[chainNo].pixels[1].r;\r\n int fc = chains[chainNo].pixels[1].c;\r\n\r\n int dr = abs(\r\n fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n int dc = abs(\r\n fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n if (dr <= 1 && dc <= 1) {\r\n startIndex = 1;\r\n }\r\n } \/\/ end-if\r\n#endif\r\n\r\n \/* Start a new chain & copy pixels from the new chain *\/\r\n for (int l = startIndex; l < chains[chainNo].len; l++) {\r\n map->segments[noSegments].pixels[noSegmentPixels++] =\r\n chains[chainNo].pixels[l];\r\n } \/\/ end-for\r\n\r\n chains[chainNo].len = 0; \/\/ Mark as copied\r\n } \/\/ end-for\r\n } \/\/ end-if\r\n\r\n map->segments[noSegments].noPixels = noSegmentPixels;\r\n totalPixels += noSegmentPixels;\r\n\r\n \/\/ See if the first pixel can be cleaned up\r\n int fr = map->segments[noSegments].pixels[1].r;\r\n int fc = map->segments[noSegments].pixels[1].c;\r\n\r\n int dr =\r\n abs(fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n int dc =\r\n abs(fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n if (dr <= 1 && dc <= 1) {\r\n map->segments[noSegments].pixels++;\r\n map->segments[noSegments].noPixels--;\r\n } \/\/ end-if\r\n\r\n noSegments++;\r\n\r\n \/\/ Copy the rest of the long chains here\r\n for (int k = 2; k < noChains; k++) {\r\n if (chains[k].len < 2) continue;\r\n\r\n totalLen = LongestChain(chains, k);\r\n\r\n \/\/ If long enough, copy\r\n \/\/ if (totalLen >= 12){\r\n if (totalLen >= 10) {\r\n map->segments[noSegments].pixels = &map->pixels[totalPixels];\r\n\r\n \/\/ Retrieve the chainNos\r\n int count = RetrieveChainNos(chains, k, chainNos);\r\n\r\n \/\/ Copy the pixels\r\n noSegmentPixels = 0;\r\n for (int k = 0; k < count; k++) {\r\n int chainNo = chainNos[k];\r\n\r\n#if 1\r\n \/* See if we can erase some pixels from the last chain. This is for\r\n * cleanup *\/\r\n int fr = chains[chainNo].pixels[0].r;\r\n int fc = chains[chainNo].pixels[0].c;\r\n\r\n int index = noSegmentPixels - 2;\r\n while (index >= 0) {\r\n int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n if (dr <= 1 && dc <= 1) {\r\n \/\/ neighbors. Erase last pixel\r\n noSegmentPixels--;\r\n index--;\r\n } else\r\n break;\r\n } \/\/ end-while\r\n\r\n int startIndex = 0;\r\n int chainLen = chains[chainNo].len;\r\n if (chainLen > 1) {\r\n int fr = chains[chainNo].pixels[1].r;\r\n int fc = chains[chainNo].pixels[1].c;\r\n\r\n int dr = abs(\r\n fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n int dc = abs(\r\n fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n if (dr <= 1 && dc <= 1) {\r\n startIndex = 1;\r\n }\r\n } \/\/ end-if\r\n#endif\r\n \/* Start a new chain & copy pixels from the new chain *\/\r\n for (int l = startIndex; l < chains[chainNo].len; l++) {\r\n map->segments[noSegments].pixels[noSegmentPixels++] =\r\n chains[chainNo].pixels[l];\r\n } \/\/ end-for\r\n\r\n chains[chainNo].len = 0; \/\/ Mark as copied\r\n } \/\/ end-for\r\n\r\n map->segments[noSegments].noPixels = noSegmentPixels;\r\n totalPixels += noSegmentPixels;\r\n\r\n noSegments++;\r\n } \/\/ end-if\r\n } \/\/ end-for\r\n\r\n } \/\/ end-else\r\n\r\n } \/\/ end-for-outer\r\n\r\n map->noSegments = noSegments;\r\n\r\n delete A;\r\n delete chains;\r\n delete stack;\r\n delete pixels;\r\n delete chainNos;\r\n} \/\/ end-JoinAnchorPointsUsingSortedAnchors\r\n\r\n\/\/\/-----------------------------------------------------------------------------------\r\n\/\/\/ Join anchors starting with the anchor having the maximum gradient value.\r\n\/\/\/ To do this, we need to first sort the anchors\r\n\/\/\/ Uses 4 directions during anchor join (0, 45, 90 and 135 degrees)\r\n\/\/\/\r\n\/\/ static\r\n\/\/ void JoinAnchorPointsUsingSortedAnchors4Dirs(short *gradImg,\r\n\/\/ unsigned char *dirImg,\r\n\/\/ EdgeMap *map, int GRADIENT_THRESH,\r\n\/\/ int MIN_PATH_LEN) {\r\n\/\/ int width = map->width;\r\n\/\/ int height = map->height;\r\n\r\n\/\/ unsigned char *edgeImg = map->edgeImg;\r\n\/\/ int *chainNos = new int[(width + height) * 8];\r\n\r\n\/\/ Pixel *pixels = new Pixel[width * height];\r\n\/\/ StackNode *stack = new StackNode[width * height];\r\n\/\/ Chain *chains = new Chain[width * height];\r\n\r\n\/\/ \/\/ First Sort the anchors\r\n\/\/ int noAnchors;\r\n\/\/ int *A = SortAnchorsByGradValue(gradImg, map, &noAnchors);\r\n\r\n\/\/ \/\/ Now join the anchors starting with the anchor having the greatest gradient\r\n\/\/ \/\/ value\r\n\/\/ int noSegments = 0;\r\n\/\/ int totalPixels = 0;\r\n\r\n\/\/ for (int k = noAnchors - 1; k >= 0; k--) {\r\n\/\/ int pixelOffset = A[k];\r\n\r\n\/\/ int i = pixelOffset \/ width;\r\n\/\/ int j = pixelOffset % width;\r\n\r\n\/\/ if (edgeImg[i * width + j] != ANCHOR_PIXEL) continue;\r\n\r\n\/\/ chains[0].len = 0;\r\n\/\/ chains[0].parent = -1;\r\n\/\/ chains[0].dir = 0;\r\n\/\/ chains[0].children[0] = chains[0].children[1] = -1;\r\n\/\/ chains[0].pixels = NULL;\r\n\r\n\/\/ int noChains = 1;\r\n\/\/ int len = 0;\r\n\/\/ int duplicatePixelCount = 0;\r\n\r\n\/\/ int top = -1; \/\/ top of the stack\r\n\r\n\/\/ if (dirImg[i * width + j] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ } else if (dirImg[i * width + j] == EDGE_HORIZONTAL) {\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ } else if (dirImg[i * width + j] == EDGE_45) {\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = UP_RIGHT;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = DOWN_LEFT;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ } else { \/\/ if (dirImg[i*width+j] == EDGE_135){\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = UP_LEFT;\r\n\/\/ stack[top].parent = 0;\r\n\r\n\/\/ stack[++top].r = i;\r\n\/\/ stack[top].c = j;\r\n\/\/ stack[top].dir = DOWN_RIGHT;\r\n\/\/ stack[top].parent = 0;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ \/\/ While the stack is not empty\r\n\/\/ StartOfWhile:\r\n\/\/ while (top >= 0) {\r\n\/\/ int r = stack[top].r;\r\n\/\/ int c = stack[top].c;\r\n\/\/ int dir = stack[top].dir;\r\n\/\/ int parent = stack[top].parent;\r\n\/\/ top--;\r\n\r\n\/\/ if (edgeImg[r * width + c] != EDGE_PIXEL) duplicatePixelCount++;\r\n\r\n\/\/ chains[noChains].dir = dir; \/\/ traversal direction\r\n\/\/ chains[noChains].parent = parent;\r\n\/\/ chains[noChains].children[0] = chains[noChains].children[1] = -1;\r\n\r\n\/\/ int chainLen = 0;\r\n\/\/ chains[noChains].pixels = &pixels[len];\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\r\n\/\/ if (dir == LEFT) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is horizontal. Look LEFT\r\n\/\/ \/\/\r\n\/\/ \/\/ A\r\n\/\/ \/\/ B x\r\n\/\/ \/\/ C\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup up & down pixels\r\n\/\/ if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[r * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow max. pixel to the LEFT\r\n\/\/ int A = gradImg[(r - 1) * width + c - 1];\r\n\/\/ int B = gradImg[r * width + c - 1];\r\n\/\/ int C = gradImg[(r + 1) * width + c - 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ r--;\r\n\/\/ else\r\n\/\/ r++;\r\n\/\/ } else if (C > B)\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_45) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_135){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == RIGHT) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is horizontal. Look RIGHT\r\n\/\/ \/\/\r\n\/\/ \/\/ A\r\n\/\/ \/\/ x B\r\n\/\/ \/\/ C\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup up&down pixels\r\n\/\/ if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c] = 0;\r\n\/\/ if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[r * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c++;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow max. pixel to the RIGHT\r\n\/\/ int A = gradImg[(r - 1) * width + c + 1];\r\n\/\/ int B = gradImg[r * width + c + 1];\r\n\/\/ int C = gradImg[(r + 1) * width + c + 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ r--; \/\/ A\r\n\/\/ else\r\n\/\/ r++; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ r++; \/\/ C\r\n\/\/ c++;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_45) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_135){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == UP) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is vertical. Look UP\r\n\/\/ \/\/\r\n\/\/ \/\/ A B C\r\n\/\/ \/\/ x\r\n\/\/ \/\/\r\n\/\/ \/\/ Cleanup left & right pixels\r\n\/\/ if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c - 1] = 0;\r\n\/\/ if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c + 1] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r - 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c++;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel UP\r\n\/\/ int A = gradImg[(r - 1) * width + c - 1];\r\n\/\/ int B = gradImg[(r - 1) * width + c];\r\n\/\/ int C = gradImg[(r - 1) * width + c + 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c--;\r\n\/\/ else\r\n\/\/ c++;\r\n\/\/ } else if (C > B)\r\n\/\/ c++;\r\n\/\/ r--;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_45) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_135){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == DOWN) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is vertical\r\n\/\/ \/\/\r\n\/\/ \/\/ x\r\n\/\/ \/\/ A B C\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup side pixels\r\n\/\/ if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c + 1] = 0;\r\n\/\/ if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c - 1] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r + 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel DOWN\r\n\/\/ int A = gradImg[(r + 1) * width + c - 1];\r\n\/\/ int B = gradImg[(r + 1) * width + c];\r\n\/\/ int C = gradImg[(r + 1) * width + c + 1];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c--; \/\/ A\r\n\/\/ else\r\n\/\/ c++; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ c++; \/\/ C\r\n\/\/ r++;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_45) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_135){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == UP_RIGHT) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_45) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is 45 degrees\r\n\/\/ \/\/\r\n\/\/ \/\/ C B\r\n\/\/ \/\/ x A\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup side pixels\r\n\/\/ if (edgeImg[(r - 1) * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c - 1] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c + 1] = 0;\r\n\/\/ if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c - 1] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r - 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ } else if (edgeImg[r * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ c++;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel UP-RIGHT\r\n\/\/ int A = gradImg[r * width + c + 1];\r\n\/\/ int B = gradImg[(r - 1) * width + c + 1];\r\n\/\/ int C = gradImg[(r - 1) * width + c];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c++; \/\/ A\r\n\/\/ else\r\n\/\/ r--; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ r--; \/\/ C\r\n\/\/ else {\r\n\/\/ r--;\r\n\/\/ c++;\r\n\/\/ } \/\/ B\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_135){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == DOWN_LEFT) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_45) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is 45 degrees\r\n\/\/ \/\/\r\n\/\/ \/\/ A x\r\n\/\/ \/\/ B C\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup side pixels\r\n\/\/ if (edgeImg[(r - 1) * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c - 1] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c + 1] = 0;\r\n\/\/ if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c + 1] = 0;\r\n\/\/ if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r + 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ } else if (edgeImg[r * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ c--;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel DOWN-LEFT\r\n\/\/ int A = gradImg[r * width + c - 1];\r\n\/\/ int B = gradImg[(r + 1) * width + c - 1];\r\n\/\/ int C = gradImg[(r + 1) * width + c];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c--; \/\/ A\r\n\/\/ else\r\n\/\/ r++; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ r++; \/\/ C\r\n\/\/ else {\r\n\/\/ r++;\r\n\/\/ c--;\r\n\/\/ } \/\/ B\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_135){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else if (dir == UP_LEFT) {\r\n\/\/ while (dirImg[r * width + c] == EDGE_135) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is 135 degrees\r\n\/\/ \/\/\r\n\/\/ \/\/ B C\r\n\/\/ \/\/ A x\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup side pixels\r\n\/\/ if (edgeImg[(r - 1) * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c + 1] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c - 1] = 0;\r\n\/\/ if (edgeImg[r * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c + 1] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r - 1) * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ c--;\r\n\/\/ } else if (edgeImg[(r - 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r--;\r\n\/\/ } else if (edgeImg[r * width + c - 1] >= ANCHOR_PIXEL) {\r\n\/\/ c--;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel UP-LEFT\r\n\/\/ int A = gradImg[r * width + c - 1];\r\n\/\/ int B = gradImg[(r - 1) * width + c - 1];\r\n\/\/ int C = gradImg[(r - 1) * width + c];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c--; \/\/ A\r\n\/\/ else\r\n\/\/ r--; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ r--; \/\/ C\r\n\/\/ else {\r\n\/\/ r--;\r\n\/\/ c--;\r\n\/\/ } \/\/ B\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_45){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[0] = noChains;\r\n\/\/ noChains++;\r\n\r\n\/\/ } else { \/\/ if (dir == DOWN_RIGHT){\r\n\/\/ while (dirImg[r * width + c] == EDGE_135) {\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ \/\/ The edge is 135 degrees\r\n\/\/ \/\/\r\n\/\/ \/\/ x C\r\n\/\/ \/\/ A B\r\n\/\/ \/\/\r\n\/\/ \/\/ cleanup side pixels\r\n\/\/ if (edgeImg[(r - 1) * width + c + 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c + 1] = 0;\r\n\/\/ if (edgeImg[(r + 1) * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r + 1) * width + c - 1] = 0;\r\n\/\/ if (edgeImg[r * width + c - 1] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[r * width + c - 1] = 0;\r\n\/\/ if (edgeImg[(r - 1) * width + c] == ANCHOR_PIXEL)\r\n\/\/ edgeImg[(r - 1) * width + c] = 0;\r\n\r\n\/\/ \/\/ Look if there is an edge pixel in the neighbors\r\n\/\/ if (edgeImg[(r + 1) * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ c++;\r\n\/\/ } else if (edgeImg[(r + 1) * width + c] >= ANCHOR_PIXEL) {\r\n\/\/ r++;\r\n\/\/ } else if (edgeImg[r * width + c + 1] >= ANCHOR_PIXEL) {\r\n\/\/ c++;\r\n\/\/ } else {\r\n\/\/ \/\/ else -- follow the max. pixel DOWN-RIGHT\r\n\/\/ int A = gradImg[r * width + c + 1];\r\n\/\/ int B = gradImg[(r + 1) * width + c + 1];\r\n\/\/ int C = gradImg[(r + 1) * width + c];\r\n\r\n\/\/ if (A > B) {\r\n\/\/ if (A > C)\r\n\/\/ c++; \/\/ A\r\n\/\/ else\r\n\/\/ r++; \/\/ C\r\n\/\/ } else if (C > B)\r\n\/\/ r++; \/\/ C\r\n\/\/ else {\r\n\/\/ r++;\r\n\/\/ c++;\r\n\/\/ } \/\/ B\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (edgeImg[r * width + c] == EDGE_PIXEL ||\r\n\/\/ gradImg[r * width + c] < GRADIENT_THRESH) {\r\n\/\/ if (chainLen > 0) {\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-if\r\n\/\/ goto StartOfWhile;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ pixels[len].r = r;\r\n\/\/ pixels[len].c = c;\r\n\/\/ len++;\r\n\/\/ chainLen++;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (dirImg[r * width + c] == EDGE_HORIZONTAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else if (dirImg[r * width + c] == EDGE_VERTICAL) {\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ } else { \/\/ if (dirImg[r*width+c] == EDGE_45){\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = UP_RIGHT;\r\n\/\/ stack[top].parent = noChains;\r\n\r\n\/\/ stack[++top].r = r;\r\n\/\/ stack[top].c = c;\r\n\/\/ stack[top].dir = DOWN_LEFT;\r\n\/\/ stack[top].parent = noChains;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ len--;\r\n\/\/ chainLen--;\r\n\r\n\/\/ chains[noChains].len = chainLen;\r\n\/\/ chains[parent].children[1] = noChains;\r\n\/\/ noChains++;\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (len - duplicatePixelCount < MIN_PATH_LEN) {\r\n\/\/ for (int k = 0; k < len; k++) {\r\n\/\/ edgeImg[pixels[k].r * width + pixels[k].c] = 0;\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ } else {\r\n\/\/ map->segments[noSegments].pixels = &map->pixels[totalPixels];\r\n\r\n\/\/ int totalLen = LongestChain(chains, chains[0].children[1]);\r\n\/\/ int noSegmentPixels = 0;\r\n\r\n\/\/ if (totalLen > 0) {\r\n\/\/ \/\/ Retrieve the chainNos\r\n\/\/ int count = RetrieveChainNos(chains, chains[0].children[1], chainNos);\r\n\r\n\/\/ \/\/ Copy these pixels in the reverse order\r\n\/\/ for (int k = count - 1; k >= 0; k--) {\r\n\/\/ int chainNo = chainNos[k];\r\n\r\n\/\/ #if 1\r\n\/\/ \/* See if we can erase some pixels from the last chain. This is for\r\n\/\/ * cleanup *\/\r\n\/\/ int fr = chains[chainNo].pixels[chains[chainNo].len - 1].r;\r\n\/\/ int fc = chains[chainNo].pixels[chains[chainNo].len - 1].c;\r\n\r\n\/\/ int index = noSegmentPixels - 2;\r\n\/\/ while (index >= 0) {\r\n\/\/ int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n\/\/ int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ \/\/ neighbors. Erase last pixel\r\n\/\/ noSegmentPixels--;\r\n\/\/ index--;\r\n\/\/ } else\r\n\/\/ break;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ if (chains[chainNo].len > 1) {\r\n\/\/ fr = chains[chainNo].pixels[chains[chainNo].len - 2].r;\r\n\/\/ fc = chains[chainNo].pixels[chains[chainNo].len - 2].c;\r\n\r\n\/\/ int dr = abs(\r\n\/\/ fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc = abs(\r\n\/\/ fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) chains[chainNo].len--;\r\n\/\/ } \/\/ end-if\r\n\/\/ #endif\r\n\r\n\/\/ for (int l = chains[chainNo].len - 1; l >= 0; l--) {\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels++] =\r\n\/\/ chains[chainNo].pixels[l];\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ chains[chainNo].len = 0; \/\/ Mark as copied\r\n\/\/ } \/\/ end-for\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ totalLen = LongestChain(chains, chains[0].children[0]);\r\n\/\/ if (totalLen > 1) {\r\n\/\/ \/\/ Retrieve the chainNos\r\n\/\/ int count = RetrieveChainNos(chains, chains[0].children[0], chainNos);\r\n\r\n\/\/ \/\/ Copy these chains in the forward direction. Skip the first pixel of\r\n\/\/ \/\/ the first chain due to repetition with the last pixel of the previous\r\n\/\/ \/\/ chain\r\n\/\/ int lastChainNo = chainNos[0];\r\n\/\/ chains[lastChainNo].pixels++;\r\n\/\/ chains[lastChainNo].len--;\r\n\r\n\/\/ for (int k = 0; k < count; k++) {\r\n\/\/ int chainNo = chainNos[k];\r\n\r\n\/\/ #if 1\r\n\/\/ \/* See if we can erase some pixels from the last chain. This is for\r\n\/\/ * cleanup *\/\r\n\/\/ int fr = chains[chainNo].pixels[0].r;\r\n\/\/ int fc = chains[chainNo].pixels[0].c;\r\n\r\n\/\/ int index = noSegmentPixels - 2;\r\n\/\/ while (index >= 0) {\r\n\/\/ int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n\/\/ int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ \/\/ neighbors. Erase last pixel\r\n\/\/ noSegmentPixels--;\r\n\/\/ index--;\r\n\/\/ } else\r\n\/\/ break;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ int startIndex = 0;\r\n\/\/ int chainLen = chains[chainNo].len;\r\n\/\/ if (chainLen > 1) {\r\n\/\/ int fr = chains[chainNo].pixels[1].r;\r\n\/\/ int fc = chains[chainNo].pixels[1].c;\r\n\r\n\/\/ int dr = abs(\r\n\/\/ fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc = abs(\r\n\/\/ fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ startIndex = 1;\r\n\/\/ }\r\n\/\/ } \/\/ end-if\r\n\/\/ #endif\r\n\r\n\/\/ \/* Start a new chain & copy pixels from the new chain *\/\r\n\/\/ for (int l = startIndex; l < chains[chainNo].len; l++) {\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels++] =\r\n\/\/ chains[chainNo].pixels[l];\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ chains[chainNo].len = 0; \/\/ Mark as copied\r\n\/\/ } \/\/ end-for\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ map->segments[noSegments].noPixels = noSegmentPixels;\r\n\/\/ totalPixels += noSegmentPixels;\r\n\r\n\/\/ \/\/ See if the first pixel can be cleaned up\r\n\/\/ int fr = map->segments[noSegments].pixels[1].r;\r\n\/\/ int fc = map->segments[noSegments].pixels[1].c;\r\n\r\n\/\/ int dr =\r\n\/\/ abs(fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc =\r\n\/\/ abs(fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ map->segments[noSegments].pixels++;\r\n\/\/ map->segments[noSegments].noPixels--;\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ noSegments++;\r\n\r\n\/\/ \/\/ Copy the rest of the long chains here\r\n\/\/ for (int k = 2; k < noChains; k++) {\r\n\/\/ if (chains[k].len < 2) continue;\r\n\r\n\/\/ totalLen = LongestChain(chains, k);\r\n\r\n\/\/ \/\/ If long enough, copy\r\n\/\/ \/\/ if (totalLen >= 12){\r\n\/\/ if (totalLen >= 10) {\r\n\/\/ map->segments[noSegments].pixels = &map->pixels[totalPixels];\r\n\r\n\/\/ \/\/ Retrieve the chainNos\r\n\/\/ int count = RetrieveChainNos(chains, k, chainNos);\r\n\r\n\/\/ \/\/ Copy the pixels\r\n\/\/ noSegmentPixels = 0;\r\n\/\/ for (int k = 0; k < count; k++) {\r\n\/\/ int chainNo = chainNos[k];\r\n\r\n\/\/ #if 1\r\n\/\/ \/* See if we can erase some pixels from the last chain. This is for\r\n\/\/ * cleanup *\/\r\n\/\/ int fr = chains[chainNo].pixels[0].r;\r\n\/\/ int fc = chains[chainNo].pixels[0].c;\r\n\r\n\/\/ int index = noSegmentPixels - 2;\r\n\/\/ while (index >= 0) {\r\n\/\/ int dr = abs(fr - map->segments[noSegments].pixels[index].r);\r\n\/\/ int dc = abs(fc - map->segments[noSegments].pixels[index].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ \/\/ neighbors. Erase last pixel\r\n\/\/ noSegmentPixels--;\r\n\/\/ index--;\r\n\/\/ } else\r\n\/\/ break;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ int startIndex = 0;\r\n\/\/ int chainLen = chains[chainNo].len;\r\n\/\/ if (chainLen > 1) {\r\n\/\/ int fr = chains[chainNo].pixels[1].r;\r\n\/\/ int fc = chains[chainNo].pixels[1].c;\r\n\r\n\/\/ int dr = abs(\r\n\/\/ fr - map->segments[noSegments].pixels[noSegmentPixels - 1].r);\r\n\/\/ int dc = abs(\r\n\/\/ fc - map->segments[noSegments].pixels[noSegmentPixels - 1].c);\r\n\r\n\/\/ if (dr <= 1 && dc <= 1) {\r\n\/\/ startIndex = 1;\r\n\/\/ }\r\n\/\/ } \/\/ end-if\r\n\/\/ #endif\r\n\/\/ \/* Start a new chain & copy pixels from the new chain *\/\r\n\/\/ for (int l = startIndex; l < chains[chainNo].len; l++) {\r\n\/\/ map->segments[noSegments].pixels[noSegmentPixels++] =\r\n\/\/ chains[chainNo].pixels[l];\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ chains[chainNo].len = 0; \/\/ Mark as copied\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ map->segments[noSegments].noPixels = noSegmentPixels;\r\n\/\/ totalPixels += noSegmentPixels;\r\n\r\n\/\/ noSegments++;\r\n\/\/ } \/\/ end-if\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ } \/\/ end-for-outer\r\n\r\n\/\/ map->noSegments = noSegments;\r\n\r\n\/\/ delete A;\r\n\/\/ delete chains;\r\n\/\/ delete stack;\r\n\/\/ delete pixels;\r\n\/\/ delete chainNos;\r\n\/\/ } \/\/ end-JoinAnchorPointsUsingSortedAnchors4Dirs\r\n\r\n\/\/\/----------------------------------------------------------------------------------------------\r\n\/\/\/ Detect edges by edge drawing method\r\n\/\/\/\r\nEdgeMap *DoDetectEdgesByED(short *gradImg, unsigned char *dirImg, int width,\r\n int height, int GRADIENT_THRESH, int ANCHOR_THRESH) {\r\n \/\/ Check parameters for sanity\r\n if (GRADIENT_THRESH < 1) GRADIENT_THRESH = 1;\r\n if (ANCHOR_THRESH < 0) ANCHOR_THRESH = 0;\r\n int SCAN_INTERVAL = 1; \/\/ 2\r\n int MIN_PATH_LEN = 10; \/\/ 10 pixels\r\n\r\n \/\/ Edge map to be returned\r\n EdgeMap *map = new EdgeMap(width, height);\r\n\r\n \/*------------ COMPUTE ANCHORS -------------------*\/\r\n ComputeAnchorPoints(gradImg, dirImg, map, GRADIENT_THRESH, ANCHOR_THRESH,\r\n SCAN_INTERVAL);\r\n\r\n \/*------------ JOIN ANCHORS -------------------*\/\r\n JoinAnchorPointsUsingSortedAnchors(gradImg, dirImg, map, GRADIENT_THRESH,\r\n MIN_PATH_LEN);\r\n \/\/ JoinAnchorPoints(gradImg, dirImg, map, GRADIENT_THRESH, MIN_PATH_LEN);\r\n\r\n return map;\r\n} \/\/ DoDetectEdgesByED\r\n\r\n\/\/\/----------------------------------------------------------------------------------------------\r\n\/\/\/ Detect edges by edge drawing method\r\n\/\/\/\r\n\/\/ EdgeMap *DoDetectEdgesByED4Dirs(short *gradImg, unsigned char *dirImg,\r\n\/\/ int width, int height, int GRADIENT_THRESH,\r\n\/\/ int ANCHOR_THRESH) {\r\n\/\/ \/\/ Check parameters for sanity\r\n\/\/ if (GRADIENT_THRESH < 1) GRADIENT_THRESH = 1;\r\n\/\/ if (ANCHOR_THRESH < 0) ANCHOR_THRESH = 0;\r\n\/\/ int SCAN_INTERVAL = 1; \/\/ 2\r\n\/\/ int MIN_PATH_LEN = 10; \/\/ 10 pixels\r\n\r\n\/\/ \/\/ Edge map to be returned\r\n\/\/ EdgeMap *map = new EdgeMap(width, height);\r\n\r\n\/\/ \/*------------ COMPUTE ANCHORS -------------------*\/\r\n\/\/ ComputeAnchorPoints4Dirs(gradImg, dirImg, map, GRADIENT_THRESH, ANCHOR_THRESH,\r\n\/\/ SCAN_INTERVAL);\r\n\r\n\/\/ \/*------------ JOIN ANCHORS -------------------*\/\r\n\/\/ JoinAnchorPointsUsingSortedAnchors4Dirs(gradImg, dirImg, map, GRADIENT_THRESH,\r\n\/\/ MIN_PATH_LEN);\r\n\r\n\/\/ return map;\r\n\/\/ } \/\/ DoDetectEdgesByED4Dirs\r\n\r\n\/**************************** ALTERNATIVE ED THAT DOES NOT USE EDGE DIRECTIONS\r\n * FOR LINKING ***********************\/\r\n\/\/ #if 0\r\n\/\/ \/\/\/-------------------------- Original EDWalk ------------------------------\r\n\/\/ \/\/\/-------------------------------------------------------------------------\r\n\/\/ \/\/\/ Walks from (r, c) using the grad image (uses 8 directions)\r\n\/\/ \/\/\/\r\n\/\/ int EDWalk(short *gradImg, EdgeMap *map, int GRADIENT_THRESH, int r, int c, int dir, Pixel *pixels){\r\n\/\/ unsigned char *edgeImg = map->edgeImg;\r\n\r\n\/\/ int width = map->width;\r\n\/\/ int height = map->height;\r\n\r\n\/\/ int count = 0;\r\n\/\/ while (1){\r\n\/\/ if (r<=0 || r>=height-1) return count;\r\n\/\/ if (c<=0 || c>=width-1) return count;\r\n\r\n\/\/ pixels[count].r = r;\r\n\/\/ pixels[count].c = c;\r\n\/\/ count++;\r\n\r\n\/\/ edgeImg[r*width+c] = EDGE_PIXEL;\r\n\r\n\/\/ int maxGrad = GRADIENT_THRESH-1;\r\n\/\/ int nextDir = -1;\r\n\/\/ int grad;\r\n\/\/ int nr=r, nc=c;\r\n\r\n\/\/ if (dir == UP_LEFT){\r\n\/\/ \/\/ Left\r\n\/\/ if (edgeImg[r*width+c-1] == EDGE_PIXEL) return count; \r\n\/\/ grad = gradImg[r*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r; nc = c-1; nextDir = LEFT;}\r\n\r\n\/\/ \/\/ Up\r\n\/\/ if (edgeImg[(r-1)*width+c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c; nextDir = UP;}\r\n\r\n\/\/ \/\/ Up-Left\r\n\/\/ if (edgeImg[(r-1)*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c-1; nextDir = UP_LEFT;}\r\n\r\n\/\/ } else if (dir == UP){\r\n\/\/ \/\/ Up\r\n\/\/ if (edgeImg[(r-1)*width+c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c; nextDir = UP;}\r\n\r\n\/\/ \/\/ Up-Left\r\n\/\/ if (edgeImg[(r-1)*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c-1; nextDir = UP_LEFT;}\r\n\r\n\/\/ \/\/ Up-Right\r\n\/\/ if (edgeImg[(r-1)*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c+1; nextDir = UP_RIGHT;}\r\n\r\n\/\/ } else if (dir == UP_RIGHT){\r\n\/\/ \/\/ Up\r\n\/\/ if (edgeImg[(r-1)*width+c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c; nextDir = UP;}\r\n\r\n\/\/ \/\/ Right\r\n\/\/ if (edgeImg[r*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r; nc = c+1; nextDir = RIGHT;}\r\n\r\n\/\/ \/\/ Up-Right\r\n\/\/ if (edgeImg[(r-1)*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c+1; nextDir = UP_RIGHT;}\r\n\r\n\/\/ } else if (dir == RIGHT){\r\n\/\/ \/\/ Right\r\n\/\/ if (edgeImg[r*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r; nc = c+1; nextDir = RIGHT;}\r\n\r\n\/\/ \/\/ Up-Right\r\n\/\/ if (edgeImg[(r-1)*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c+1; nextDir = UP_RIGHT;}\r\n\r\n\/\/ \/\/ Down-Right\r\n\/\/ if (edgeImg[(r+1)*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c+1; nextDir = DOWN_RIGHT;}\r\n\r\n\/\/ } else if (dir == DOWN_RIGHT){\r\n\/\/ \/\/ Right\r\n\/\/ if (edgeImg[r*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r; nc = c+1; nextDir = RIGHT;}\r\n\r\n\/\/ \/\/ Down\r\n\/\/ if (edgeImg[(r+1)*width+c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c; nextDir = DOWN;}\r\n\r\n\/\/ \/\/ Down-Right\r\n\/\/ if (edgeImg[(r+1)*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c+1; nextDir = DOWN_RIGHT;}\r\n\r\n\/\/ } else if (dir == DOWN){\r\n\/\/ \/\/ Down\r\n\/\/ if (edgeImg[(r+1)*width+c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c; nextDir = DOWN;}\r\n\r\n\/\/ \/\/ Down-Right\r\n\/\/ if (edgeImg[(r+1)*width+c+1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c+1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c+1; nextDir = DOWN_RIGHT;}\r\n\r\n\/\/ \/\/ Down-Left\r\n\/\/ if (edgeImg[(r+1)*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c-1; nextDir = DOWN_LEFT;}\r\n\r\n\/\/ } else if (dir == DOWN_LEFT){\r\n\/\/ \/\/ Down\r\n\/\/ if (edgeImg[(r+1)*width+c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c; nextDir = DOWN;}\r\n\r\n\/\/ \/\/ Left\r\n\/\/ if (edgeImg[r*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r; nc = c-1; nextDir = LEFT;}\r\n\r\n\/\/ \/\/ Down-Left\r\n\/\/ if (edgeImg[(r+1)*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c-1; nextDir = DOWN_LEFT;}\r\n\r\n\/\/ } else { \/\/ (dir == LEFT){\r\n\/\/ \/\/ Left\r\n\/\/ if (edgeImg[r*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r; nc = c-1; nextDir = LEFT;}\r\n\r\n\/\/ \/\/ Down-Left\r\n\/\/ if (edgeImg[(r+1)*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r+1)*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r+1; nc = c-1; nextDir = DOWN_LEFT;}\r\n\r\n\/\/ \/\/ Up-Left\r\n\/\/ if (edgeImg[(r-1)*width+c-1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r-1)*width+c-1];\r\n\/\/ if (grad > maxGrad){maxGrad = grad; nr = r-1; nc = c-1; nextDir = UP_LEFT;}\r\n\/\/ } \/\/ end-else \r\n\r\n\/\/ if (nextDir < 0) break;\r\n\/\/ r = nr;\r\n\/\/ c = nc;\r\n\/\/ dir = nextDir;\r\n\/\/ } \/\/end-while\r\n\r\n\/\/ return count;\r\n\/\/ } \/\/end-EDWalk\r\n\/\/ #else\r\n\/\/ \/\/\/------------------------------ New EDWalk -------------------------------\r\n\/\/ \/\/\/-------------------------------------------------------------------------\r\n\/\/ \/\/\/ Walks from (r, c) using the grad image (uses 8 directions)\r\n\/\/ \/\/\/\r\n\/\/ int EDWalk(short *gradImg, EdgeMap *map, int GRADIENT_THRESH, int r, int c,\r\n\/\/ int dir, Pixel *pixels) {\r\n\/\/ unsigned char *edgeImg = map->edgeImg;\r\n\r\n\/\/ int width = map->width;\r\n\/\/ int height = map->height;\r\n\r\n\/\/ int count = 0;\r\n\/\/ while (1) {\r\n\/\/ if (r <= 0 || r >= height - 1) return count;\r\n\/\/ if (c <= 0 || c >= width - 1) return count;\r\n\r\n\/\/ pixels[count].r = r;\r\n\/\/ pixels[count].c = c;\r\n\/\/ count++;\r\n\r\n\/\/ edgeImg[r * width + c] = EDGE_PIXEL;\r\n\r\n\/\/ int maxGrad = GRADIENT_THRESH - 1;\r\n\/\/ int nextDir = -1;\r\n\/\/ int grad;\r\n\/\/ int nr = r, nc = c;\r\n\r\n\/\/ if (dir == UP_LEFT) {\r\n\/\/ \/\/ Left\r\n\/\/ if (edgeImg[r * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = LEFT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Up\r\n\/\/ if (edgeImg[(r - 1) * width + c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = UP;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Up-Left\r\n\/\/ if (edgeImg[(r - 1) * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = UP_LEFT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at up-right & down-left & pick the max\r\n\/\/ if (gradImg[(r - 1) * width + c + 1] >\r\n\/\/ gradImg[(r + 1) * width + c - 1]) {\r\n\/\/ grad = gradImg[(r - 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = UP_RIGHT;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[(r + 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = DOWN_LEFT;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ } else if (dir == UP) {\r\n\/\/ \/\/ Up\r\n\/\/ if (edgeImg[(r - 1) * width + c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = UP;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Up-Left\r\n\/\/ if (edgeImg[(r - 1) * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = UP_LEFT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Up-Right\r\n\/\/ if (edgeImg[(r - 1) * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = UP_RIGHT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at left & right & pick the max\r\n\/\/ if (gradImg[r * width + c - 1] > gradImg[r * width + c + 1]) {\r\n\/\/ grad = gradImg[r * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = LEFT;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[r * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = RIGHT;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ } else if (dir == UP_RIGHT) {\r\n\/\/ \/\/ Up\r\n\/\/ if (edgeImg[(r - 1) * width + c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = UP;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Right\r\n\/\/ if (edgeImg[r * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = RIGHT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Up-Right\r\n\/\/ if (edgeImg[(r - 1) * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = UP_RIGHT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at up-left & down-right & pick the max\r\n\/\/ if (gradImg[(r - 1) * width + c - 1] >\r\n\/\/ gradImg[(r + 1) * width + c + 1]) {\r\n\/\/ grad = gradImg[(r - 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = UP_LEFT;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[(r + 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = DOWN_RIGHT;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ } else if (dir == RIGHT) {\r\n\/\/ \/\/ Right\r\n\/\/ if (edgeImg[r * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = RIGHT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Up-Right\r\n\/\/ if (edgeImg[(r - 1) * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = UP_RIGHT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Down-Right\r\n\/\/ if (edgeImg[(r + 1) * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = DOWN_RIGHT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at up & down & pick the max\r\n\/\/ if (gradImg[(r - 1) * width + c] > gradImg[(r + 1) * width + c]) {\r\n\/\/ grad = gradImg[(r - 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = UP;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[(r + 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = DOWN;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ } else if (dir == DOWN_RIGHT) {\r\n\/\/ \/\/ Right\r\n\/\/ if (edgeImg[r * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = RIGHT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Down\r\n\/\/ if (edgeImg[(r + 1) * width + c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = DOWN;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Down-Right\r\n\/\/ if (edgeImg[(r + 1) * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = DOWN_RIGHT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at up-right & down-left & pick the max\r\n\/\/ if (gradImg[(r - 1) * width + c + 1] >\r\n\/\/ gradImg[(r + 1) * width + c - 1]) {\r\n\/\/ grad = gradImg[(r - 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = UP_RIGHT;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[(r + 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = DOWN_LEFT;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ } else if (dir == DOWN) {\r\n\/\/ \/\/ Down\r\n\/\/ if (edgeImg[(r + 1) * width + c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = DOWN;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Down-Right\r\n\/\/ if (edgeImg[(r + 1) * width + c + 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = DOWN_RIGHT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Down-Left\r\n\/\/ if (edgeImg[(r + 1) * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = DOWN_LEFT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at left & right & pick the max\r\n\/\/ if (gradImg[r * width + c - 1] > gradImg[r * width + c + 1]) {\r\n\/\/ grad = gradImg[r * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = LEFT;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[r * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = RIGHT;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ } else if (dir == DOWN_LEFT) {\r\n\/\/ \/\/ Down\r\n\/\/ if (edgeImg[(r + 1) * width + c] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = DOWN;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Left\r\n\/\/ if (edgeImg[r * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = LEFT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Down-Left\r\n\/\/ if (edgeImg[(r + 1) * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = DOWN_LEFT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at up-left & down-right & pick the max\r\n\/\/ if (gradImg[(r - 1) * width + c - 1] >\r\n\/\/ gradImg[(r + 1) * width + c + 1]) {\r\n\/\/ grad = gradImg[(r - 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = UP_LEFT;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[(r + 1) * width + c + 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c + 1;\r\n\/\/ nextDir = DOWN_RIGHT;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\r\n\/\/ } else { \/\/ (dir == LEFT){\r\n\/\/ \/\/ Left\r\n\/\/ if (edgeImg[r * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[r * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = LEFT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Down-Left\r\n\/\/ if (edgeImg[(r + 1) * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r + 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = DOWN_LEFT;\r\n\/\/ }\r\n\r\n\/\/ \/\/ Up-Left\r\n\/\/ if (edgeImg[(r - 1) * width + c - 1] == EDGE_PIXEL) return count;\r\n\/\/ grad = gradImg[(r - 1) * width + c - 1];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c - 1;\r\n\/\/ nextDir = UP_LEFT;\r\n\/\/ }\r\n\r\n\/\/ if (nextDir < 0) {\r\n\/\/ \/\/ If still not found, look at up & down & pick the max\r\n\/\/ if (gradImg[(r - 1) * width + c] > gradImg[(r + 1) * width + c]) {\r\n\/\/ grad = gradImg[(r - 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r - 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = UP;\r\n\/\/ }\r\n\/\/ } else {\r\n\/\/ grad = gradImg[(r + 1) * width + c];\r\n\/\/ if (grad > maxGrad) {\r\n\/\/ maxGrad = grad;\r\n\/\/ nr = r + 1;\r\n\/\/ nc = c;\r\n\/\/ nextDir = DOWN;\r\n\/\/ }\r\n\/\/ } \/\/ end-else\r\n\/\/ } \/\/ end-if\r\n\/\/ } \/\/ end-else\r\n\r\n\/\/ if (nextDir < 0) break;\r\n\/\/ if (edgeImg[nr * width + nc] == EDGE_PIXEL) return count;\r\n\r\n\/\/ r = nr;\r\n\/\/ c = nc;\r\n\/\/ dir = nextDir;\r\n\/\/ } \/\/ end-while\r\n\r\n\/\/ return count;\r\n\/\/ } \/\/ end-EDWalk\r\n\/\/ #endif\r\n\r\n\/\/ \/\/\/------------------------------------------------------------------------------------------------\r\n\/\/ \/\/\/ Alternative anchor linking algorithm that works only by walking over the\r\n\/\/ \/\/\/ maximas of the gradImg. Does not use edge directions\r\n\/\/ \/\/\/\r\n\/\/ void JoinAnchorPointsUsingSortedAnchors(short *gradImg, EdgeMap *map,\r\n\/\/ int GRADIENT_THRESH, int MIN_PATH_LEN) {\r\n\/\/ int width = map->width;\r\n\/\/ int height = map->height;\r\n\r\n\/\/ unsigned char *edgeImg = map->edgeImg;\r\n\/\/ Pixel *tmpPixels = new Pixel[width * height];\r\n\r\n\/\/ int noSegments = 0;\r\n\/\/ int totalLen = 0;\r\n\r\n\/\/ \/\/ Sort the anchors\r\n\/\/ int noAnchors;\r\n\/\/ int *A = SortAnchorsByGradValue(gradImg, map, &noAnchors);\r\n\r\n\/\/ \/\/ Go over the anchors in sorted order\r\n\/\/ for (int k = noAnchors - 1; k >= 0; k--) {\r\n\/\/ int pixelOffset = A[k];\r\n\r\n\/\/ int i = pixelOffset \/ width;\r\n\/\/ int j = pixelOffset % width;\r\n\r\n\/\/ if (edgeImg[i * width + j] != ANCHOR_PIXEL) continue;\r\n\r\n\/\/ int dir1 = LEFT;\r\n\/\/ int dir2 = RIGHT;\r\n\/\/ int maxGrad = gradImg[i * width + j - 1];\r\n\r\n\/\/ if (gradImg[(i - 1) * width + j] > maxGrad) {\r\n\/\/ maxGrad = gradImg[(i - 1) * width + j];\r\n\/\/ dir1 = UP;\r\n\/\/ dir2 = DOWN;\r\n\/\/ }\r\n\/\/ if (gradImg[(i + 1) * width + j] > maxGrad) {\r\n\/\/ maxGrad = gradImg[(i + 1) * width + j];\r\n\/\/ dir1 = DOWN;\r\n\/\/ dir2 = UP;\r\n\/\/ }\r\n\/\/ if (gradImg[i * width + j + 1] > maxGrad) {\r\n\/\/ maxGrad = gradImg[i * width + j + 1];\r\n\/\/ dir1 = RIGHT;\r\n\/\/ dir2 = LEFT;\r\n\/\/ }\r\n\r\n\/\/ if (gradImg[(i - 1) * width + j - 1] > maxGrad) {\r\n\/\/ maxGrad = gradImg[(i - 1) * width + j - 1];\r\n\/\/ dir1 = UP_LEFT;\r\n\/\/ dir2 = DOWN_RIGHT;\r\n\/\/ }\r\n\/\/ if (gradImg[(i - 1) * width + j + 1] > maxGrad) {\r\n\/\/ maxGrad = gradImg[(i - 1) * width + j + 1];\r\n\/\/ dir1 = UP_RIGHT;\r\n\/\/ dir2 = DOWN_LEFT;\r\n\/\/ }\r\n\r\n\/\/ if (gradImg[(i + 1) * width + j - 1] > maxGrad) {\r\n\/\/ maxGrad = gradImg[(i + 1) * width + j - 1];\r\n\/\/ dir1 = DOWN_LEFT;\r\n\/\/ dir2 = UP_RIGHT;\r\n\/\/ }\r\n\/\/ if (gradImg[(i + 1) * width + j + 1] > maxGrad) {\r\n\/\/ maxGrad = gradImg[(i + 1) * width + j + 1];\r\n\/\/ dir1 = DOWN_RIGHT;\r\n\/\/ dir2 = UP_LEFT;\r\n\/\/ }\r\n\r\n\/\/ int len1 = EDWalk(gradImg, map, GRADIENT_THRESH, i, j, dir1, tmpPixels);\r\n\/\/ int len2 =\r\n\/\/ EDWalk(gradImg, map, GRADIENT_THRESH, i, j, dir2, tmpPixels + len1);\r\n\r\n\/\/ if (len1 + len2 - 1 < MIN_PATH_LEN) continue;\r\n\r\n\/\/ map->segments[noSegments].pixels = map->pixels + totalLen;\r\n\/\/ int len = 0;\r\n\/\/ for (int k = len1 - 1; k >= 1; k--) {\r\n\/\/ map->segments[noSegments].pixels[len] = tmpPixels[k];\r\n\/\/ len++;\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ for (int k = len1; k < len1 + len2; k++) {\r\n\/\/ map->segments[noSegments].pixels[len] = tmpPixels[k];\r\n\/\/ len++;\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ map->segments[noSegments].noPixels = len;\r\n\/\/ noSegments++;\r\n\/\/ totalLen += len;\r\n\/\/ } \/\/ end-for\r\n\r\n\/\/ map->noSegments = noSegments;\r\n\r\n\/\/ delete tmpPixels;\r\n\/\/ delete A;\r\n\/\/ } \/\/ end-JoinAnchorPointsUsingSortedAnchors\r\n\r\n\/\/ \/\/\/----------------------------------------------------------------------------------------------\r\n\/\/ \/\/\/ Alternative ED. Just uses gradImg to linking the anchors.\r\n\/\/ \/\/\/ All points in the gradient map >= GRADIENT_THRESH are assumed to be anchors.\r\n\/\/ \/\/\/ Starts anchor linking with the pixel having the max. gradient value,\r\n\/\/ \/\/\/ and walks to the neighboring pixel having the greatest gradient value.\r\n\/\/ \/\/\/ Edge directions are NOT used during anchor linking\r\n\/\/ \/\/\/\r\n\/\/ EdgeMap *DoDetectEdgesByED(short *gradImg, int width, int height,\r\n\/\/ int GRADIENT_THRESH) {\r\n\/\/ \/\/ Check parameters for sanity\r\n\/\/ if (GRADIENT_THRESH < 1) GRADIENT_THRESH = 1;\r\n\/\/ int MIN_PATH_LEN = 10; \/\/ 10 pixels\r\n\r\n\/\/ \/\/ Edge map to be returned\r\n\/\/ EdgeMap *map = new EdgeMap(width, height);\r\n\r\n\/\/ \/*------------ COMPUTE ANCHORS -------------------*\/\r\n\/\/ memset(map->edgeImg, 0, width * height);\r\n\r\n\/\/ #if 1\r\n\/\/ for (int i = 0; i < width * height; i++) {\r\n\/\/ if (gradImg[i] >= GRADIENT_THRESH) map->edgeImg[i] = ANCHOR_PIXEL;\r\n\/\/ } \/\/ end-for\r\n\/\/ #else\r\n\/\/ for (int i = 1; i < height - 1; i++) {\r\n\/\/ for (int j = 1; j < width - 1; j++) {\r\n\/\/ if (gradImg[i * width + j] < GRADIENT_THRESH) continue;\r\n\r\n\/\/ \/\/ Assume that a pixel is an anchor only if it is a local maxima in 8\r\n\/\/ \/\/ neighborhood\r\n\/\/ if (gradImg[(i - 1) * width + j - 1] > gradImg[i * width + j]) continue;\r\n\/\/ if (gradImg[(i - 1) * width + j] > gradImg[i * width + j]) continue;\r\n\/\/ if (gradImg[(i - 1) * width + j + 1] > gradImg[i * width + j]) continue;\r\n\r\n\/\/ if (gradImg[i * width + j - 1] > gradImg[i * width + j]) continue;\r\n\/\/ if (gradImg[i * width + j + 1] > gradImg[i * width + j]) continue;\r\n\r\n\/\/ if (gradImg[(i + 1) * width + j - 1] > gradImg[i * width + j]) continue;\r\n\/\/ if (gradImg[(i + 1) * width + j] > gradImg[i * width + j]) continue;\r\n\/\/ if (gradImg[(i + 1) * width + j + 1] > gradImg[i * width + j]) continue;\r\n\r\n\/\/ map->edgeImg[i * width + j] = ANCHOR_PIXEL;\r\n\/\/ } \/\/ end-for\r\n\/\/ } \/\/ end-for\r\n\/\/ #endif\r\n\r\n\/\/ \/*------------ JOIN ANCHORS -------------------*\/\r\n\/\/ JoinAnchorPointsUsingSortedAnchors(gradImg, map, GRADIENT_THRESH,\r\n\/\/ MIN_PATH_LEN);\r\n\r\n\/\/ return map;\r\n\/\/ } \/\/ end-DoDetectEdgesByED\r\n} \/\/ namespace stag\r\n","avg_line_length":33.8287131602,"max_line_length":104,"alphanum_fraction":0.4154195168} {"size":23415,"ext":"cpp","lang":"C++","max_stars_count":394.0,"content":"#include \n#include \n#include \n#include \"NimBLEHIDDevice.h\"\n#include \"HIDTypes.h\"\n#include \"HIDKeyboardTypes.h\"\n#include \n#include \"sdkconfig.h\"\n\n#include \"BleConnectionStatus.h\"\n#include \"BleGamepad.h\"\n\n#if defined(CONFIG_ARDUHAL_ESP_LOG)\n #include \"esp32-hal-log.h\"\n #define LOG_TAG \"BLEGamepad\"\n#else\n #include \"esp_log.h\"\n static const char* LOG_TAG = \"BLEGamepad\";\n#endif\n\nuint8_t tempHidReportDescriptor[150];\nint hidReportDescriptorSize = 0;\nuint8_t _hidReportId = 3;\nuint8_t reportSize = 0;\nuint8_t numOfButtonBytes = 0;\n\nBleGamepad::BleGamepad(std::string deviceName, std::string deviceManufacturer, uint8_t batteryLevel) :\n _controllerType(CONTROLLER_TYPE_GAMEPAD),\n _buttons(),\n _x(0),\n _y(0),\n _z(0),\n _rZ(0),\n _rX(0),\n _rY(0),\n _slider1(0),\n _slider2(0),\n _rudder(0),\n _throttle(0),\n _accelerator(0),\n _brake(0),\n _steering(0),\n _hat1(0),\n _hat2(0),\n _hat3(0),\n _hat4(0),\n _autoReport(true),\n _buttonCount(0),\n _hatSwitchCount(0),\n _includeXAxis(true),\n _includeYAxis(true),\n _includeZAxis(true),\n _includeRxAxis(true),\n _includeRyAxis(true),\n _includeRzAxis(true),\n _includeSlider1(true),\n _includeSlider2(true),\n _includeRudder(false),\n _includeThrottle(false),\n _includeAccelerator(false),\n _includeBrake(false),\n _includeSteering(false),\n hid(0)\n{\n this->resetButtons();\n this->deviceName = deviceName;\n this->deviceManufacturer = deviceManufacturer;\n this->batteryLevel = batteryLevel;\n this->connectionStatus = new BleConnectionStatus();\n}\n\nvoid BleGamepad::resetButtons() {\n memset(&_buttons,0,sizeof(_buttons));\n}\n\nvoid BleGamepad::setControllerType(uint8_t controllerType){\n\t_controllerType = controllerType;\n}\n \n \nvoid BleGamepad::begin(uint16_t buttonCount, uint8_t hatSwitchCount, bool includeXAxis, bool includeYAxis, bool includeZAxis, bool includeRzAxis, bool includeRxAxis, bool includeRyAxis, bool includeSlider1, bool includeSlider2, bool includeRudder, bool includeThrottle, bool includeAccelerator, bool includeBrake, bool includeSteering)\n{\n\t_buttonCount = buttonCount;\n\t_hatSwitchCount = hatSwitchCount;\n\t\n\t_includeXAxis = includeXAxis;\n\t_includeYAxis = includeYAxis;\n\t_includeZAxis = includeZAxis;\n\t_includeRzAxis = includeRzAxis;\n\t_includeRxAxis = includeRxAxis;\n\t_includeRyAxis = includeRyAxis;\n\t_includeSlider1 = includeSlider1;\n\t_includeSlider2 = includeSlider2;\n\t\n\t_includeRudder = includeRudder;\n\t_includeThrottle = includeThrottle;\n\t_includeAccelerator = includeAccelerator;\n\t_includeBrake = includeBrake;\n\t_includeSteering = includeSteering;\n\t\n\tuint8_t axisCount = 0;\n\tif (_includeXAxis){ axisCount++; }\n\tif (_includeYAxis){ axisCount++; }\n\tif (_includeZAxis){ axisCount++; }\n\tif (_includeRzAxis){ axisCount++; }\n\tif (_includeRxAxis){ axisCount++; }\n\tif (_includeRyAxis){ axisCount++; }\n\tif (_includeSlider1){ axisCount++; }\n\tif (_includeSlider2){ axisCount++; }\n\t\n\tuint8_t simulationCount = 0;\n\tif (_includeRudder){ simulationCount++; }\n\tif (_includeThrottle){ simulationCount++; }\n\tif (_includeAccelerator){ simulationCount++; }\n\tif (_includeBrake){ simulationCount++; }\n\tif (_includeSteering){ simulationCount++; }\n\t\n\t\n\tuint8_t buttonPaddingBits = 8 - (_buttonCount % 8);\n\tif(buttonPaddingBits == 8){buttonPaddingBits = 0;}\n\tuint8_t numOfAxisBytes = axisCount * 2;\n\tuint8_t numOfSimulationBytes = simulationCount * 2;\n\t\n\tnumOfButtonBytes = _buttonCount \/ 8;\n\tif( buttonPaddingBits > 0){numOfButtonBytes++;}\n\t\n\treportSize = numOfButtonBytes + numOfAxisBytes + numOfSimulationBytes + _hatSwitchCount;\n\t\n\t\n \/\/ USAGE_PAGE (Generic Desktop)\n tempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;\n tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\n \/\/ USAGE (Joystick - 0x04; Gamepad - 0x05; Multi-axis Controller - 0x08)\n tempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n tempHidReportDescriptor[hidReportDescriptorSize++] = _controllerType;\n\n \/\/ COLLECTION (Application)\n tempHidReportDescriptor[hidReportDescriptorSize++] = 0xa1;\n tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\n \/\/ REPORT_ID (Default: 3)\n tempHidReportDescriptor[hidReportDescriptorSize++] = 0x85;\n tempHidReportDescriptor[hidReportDescriptorSize++] = _hidReportId;\n\t\n\tif (_buttonCount > 0) {\n\n\t\t\/\/ USAGE_PAGE (Button)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\n\t\t\/\/ USAGE_MINIMUM (Button 1)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x19;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\n\t\t\/\/ USAGE_MAXIMUM (Up to 128 buttons possible) \n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x29;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = _buttonCount;\n\n\t\t\/\/ LOGICAL_MINIMUM (0)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x15;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x00;\n\n\t\t\/\/ LOGICAL_MAXIMUM (1)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x25;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\n\t\t\/\/ REPORT_SIZE (1)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x75;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\n\t\t\/\/ REPORT_COUNT (# of buttons)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x95;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = _buttonCount;\n\n\t\t\/\/ UNIT_EXPONENT (0)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x55;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x00;\n\n\t\t\/\/ UNIT (None)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x65;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x00;\n\n\t\t\/\/ INPUT (Data,Var,Abs)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x81;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x02;\n\n\t\tif (buttonPaddingBits > 0) {\n\t\t\t\n\t\t\t\/\/ REPORT_SIZE (1)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x75;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\n\t\t\t\/\/ REPORT_COUNT (# of padding bits)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x95;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = buttonPaddingBits;\n\t\t\t\t\t\n\t\t\t\/\/ INPUT (Const,Var,Abs)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x81;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x03;\n\t\t\t\n\t\t} \/\/ Padding Bits Needed\n\n\t} \/\/ Buttons\n\t\n\tif (axisCount > 0) {\n\t\t\/\/ USAGE_PAGE (Generic Desktop)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\t\n\t\t\/\/ USAGE (Pointer)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\n\t\t\/\/ LOGICAL_MINIMUM (-32767)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x16;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x80;\n\n\t\t\/\/ LOGICAL_MAXIMUM (+32767)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x26;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xFF;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x7F;\n\n\t\t\/\/ REPORT_SIZE (16)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x75;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x10;\n\n\t\t\/\/ REPORT_COUNT (axisCount)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x95;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = axisCount;\n\t\t\t\t\t\t\n\t\t\/\/ COLLECTION (Physical)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xA1;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x00;\n\n\t\tif (_includeXAxis == true) {\n\t\t\t\/\/ USAGE (X)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x30;\n\t\t}\n\n\t\tif (_includeYAxis == true) {\n\t\t\t\/\/ USAGE (Y)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x31;\n\t\t}\n\t\t\n\t\tif (_includeZAxis == true) {\n\t\t\t\/\/ USAGE (Z)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x32;\n\t\t}\n\t\t\n\t\tif (_includeRzAxis == true) {\n\t\t\t\/\/ USAGE (Rz)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x35;\n\t\t}\n\t\t\n\t\tif (_includeRxAxis == true) {\n\t\t\t\/\/ USAGE (Rx)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x33;\n\t\t}\n\t\t\n\t\tif (_includeRyAxis == true) {\n\t\t\t\/\/ USAGE (Ry)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x34;\n\t\t}\n\t\t\n\t\t\n\t\tif (_includeSlider1 == true) {\n\t\t\t\/\/ USAGE (Slider)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x36;\n\t\t}\n\t\t\n\t\tif (_includeSlider2 == true) {\n\t\t\t\/\/ USAGE (Slider)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x36;\n\t\t}\n\t\t\n\t\t\/\/ INPUT (Data,Var,Abs)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x81;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x02;\n\t\t\n\t\t\/\/ END_COLLECTION (Physical)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xc0;\n\t\t\n\t} \/\/ X, Y, Z, Rx, Ry, and Rz Axis\t\n\t\n\tif (simulationCount > 0) {\n\t\n\t\t\/\/ USAGE_PAGE (Simulation Controls)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x02;\n\t\t\n\t\t\/\/ LOGICAL_MINIMUM (-32767)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x16;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x80;\n\n\t\t\/\/ LOGICAL_MAXIMUM (+32767)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x26;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xFF;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x7F;\n\n\t\t\/\/ REPORT_SIZE (16)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x75;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x10;\n\n\t\t\/\/ REPORT_COUNT (simulationCount)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x95;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = simulationCount;\n\n\t\t\/\/ COLLECTION (Physical)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xA1;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x00;\n\n\t\tif (includeRudder == true) {\n\t\t\t\/\/ USAGE (Rudder)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xBA;\n\t\t}\n\n\t\tif (includeThrottle == true) {\n\t\t\t\/\/ USAGE (Throttle)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xBB;\n\t\t}\n\n\t\tif (includeAccelerator == true) {\n\t\t\t\/\/ USAGE (Accelerator)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xC4;\n\t\t}\n\n\t\tif (includeBrake == true) {\n\t\t\t\/\/ USAGE (Brake)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xC5;\n\t\t}\n\n\t\tif (includeSteering == true) {\n\t\t\t\/\/ USAGE (Steering)\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xC8;\n\t\t}\n\n\t\t\/\/ INPUT (Data,Var,Abs)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x81;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x02;\n\t\t\n\t\t\/\/ END_COLLECTION (Physical)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xc0;\n\t\n\t} \/\/ Simulation Controls\n\t\n\tif(_hatSwitchCount > 0){\n\t\t\n\t\t\/\/ COLLECTION (Physical)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xA1;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x00;\n\t\t\n\t\t\/\/ USAGE_PAGE (Generic Desktop)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = USAGE_PAGE(1);\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\t\t\n\t\t\/\/ USAGE (Hat Switch)\n\t\tfor(int currentHatIndex = 0 ; currentHatIndex < _hatSwitchCount ; currentHatIndex++){\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = USAGE(1);\n\t\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x39;\n\t\t}\n\t\t\n\t\t\/\/ Logical Min (1)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x15;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\t\t\n\t\t\/\/ Logical Max (8)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x25;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x08;\n\t\t\n\t\t\/\/ Physical Min (0)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x35;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x00;\n\t\t\n\t\t\/\/ Physical Max (315)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x46;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x3B;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;\n\t\t\n\t\t\/\/ Unit (SI Rot : Ang Pos)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x65;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x12;\n\t\t\n\t\t\/\/ Report Size (8)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x75;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x08;\n\t\t\n\t\t\/\/ Report Count (4)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x95;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = _hatSwitchCount;\n\t\t\n\t\t\/\/ Input (Data, Variable, Absolute)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x81;\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0x42;\n\t\t\n\t\t\/\/ END_COLLECTION (Physical)\n\t\ttempHidReportDescriptor[hidReportDescriptorSize++] = 0xc0;\n\t}\n\t\n\t\/\/ END_COLLECTION (Application)\n tempHidReportDescriptor[hidReportDescriptorSize++] = 0xc0;\n\t\n xTaskCreate(this->taskServer, \"server\", 20000, (void *)this, 5, NULL);\n}\n\nvoid BleGamepad::end(void)\n{\n}\n\nvoid BleGamepad::setAxes(int16_t x, int16_t y, int16_t z, int16_t rZ, int16_t rX, int16_t rY, int16_t slider1, int16_t slider2, signed char hat1, signed char hat2, signed char hat3, signed char hat4)\n{\n\tif(x == -32768) { x = -32767; }\n\tif(y == -32768) { y = -32767; }\n\tif(z == -32768) { z = -32767; }\n\tif(rZ == -32768) { rZ = -32767; }\n\tif(rX == -32768) { rX = -32767; }\n\tif(rY == -32768) { rY = -32767; }\n\tif(slider1 == -32768) { slider1 = -32767; }\n\tif(slider2 == -32768) { slider2 = -32767; }\n\n\t_x = x;\n\t_y = y;\n\t_z = z;\n\t_rZ = rZ;\n\t_rX = rX;\n\t_rY = rY;\n\t_slider1 = slider1;\n\t_slider2 = slider2;\n\t_hat1 = hat1;\n\t_hat2 = hat2;\n\t_hat3 = hat3;\n\t_hat4 = hat4;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setSimulationControls(int16_t rudder, int16_t throttle, int16_t accelerator, int16_t brake, int16_t steering)\n{\n if(rudder == -32768) { rudder = -32767; }\n if(throttle == -32768) { throttle = -32767; }\n if(accelerator == -32768) { accelerator = -32767; }\n if(brake == -32768) { brake = -32767; }\n if(steering == -32768) { steering = -32767; }\n \n _rudder = rudder;\n _throttle = throttle;\n _accelerator = accelerator;\n _brake = brake;\n _steering = steering;\n\t\n if(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setHats(signed char hat1, signed char hat2, signed char hat3, signed char hat4)\n{\n\t_hat1 = hat1;\n\t_hat2 = hat2;\n\t_hat3 = hat3;\n\t_hat4 = hat4;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setSliders(int16_t slider1, int16_t slider2)\n{\t\n if(slider1 == -32768) { slider1 = -32767; }\n if(slider2 == -32768) { slider2 = -32767; }\n \n _slider1 = slider1;\n _slider2 = slider2;\n\n if(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::sendReport(void)\n{\n\tif (this->isConnected())\n\t{\n\t\tuint8_t currentReportIndex = 0;\n\t\t\n\t\tuint8_t m[reportSize];\n\t\t\n\t\tmemset(&m,0,sizeof(m));\n\t\tmemcpy(&m, &_buttons, sizeof(_buttons));\n\t\t\n\t\tcurrentReportIndex+=numOfButtonBytes;\n\t\t\n \t\tif(_includeXAxis){ m[currentReportIndex++] = _x;\tm[currentReportIndex++] = (_x >> 8); }\n\t\tif(_includeYAxis){ m[currentReportIndex++] = _y;\tm[currentReportIndex++] = (_y >> 8); }\n\t\tif(_includeZAxis){ m[currentReportIndex++] = _z;\tm[currentReportIndex++] = (_z >> 8); }\n\t\tif(_includeRzAxis){ m[currentReportIndex++] = _rZ; \tm[currentReportIndex++] = (_rZ >> 8); }\n\t\tif(_includeRxAxis){ m[currentReportIndex++] = _rX; \tm[currentReportIndex++] = (_rX >> 8); }\n\t\tif(_includeRyAxis){ m[currentReportIndex++] = _rY; \tm[currentReportIndex++] = (_rY >> 8); }\n\t\t\n\t\tif(_includeSlider1){ m[currentReportIndex++] = _slider1;\tm[currentReportIndex++] = (_slider1 >> 8); }\n\t\tif(_includeSlider2){ m[currentReportIndex++] = _slider2;\tm[currentReportIndex++] = (_slider2 >> 8); }\n \n\t\tif(_includeRudder){ m[currentReportIndex++] = _rudder;\tm[currentReportIndex++] = (_rudder >> 8); }\n\t\tif(_includeThrottle){ m[currentReportIndex++] = _throttle;\tm[currentReportIndex++] = (_throttle >> 8); }\n\t\tif(_includeAccelerator){ m[currentReportIndex++] = _accelerator;\tm[currentReportIndex++] = (_accelerator >> 8); }\n\t\tif(_includeBrake){ m[currentReportIndex++] = _brake; \tm[currentReportIndex++] = (_brake >> 8); }\n\t\tif(_includeSteering){ m[currentReportIndex++] = _steering; \tm[currentReportIndex++] = (_steering >> 8); }\n\t\t\n\t\tif(_hatSwitchCount > 0)\n\t\t{\n\t\t\tsigned char hats[4];\n\t\t\t\n\t\t\thats[0] = _hat1;\n\t\t\thats[1] = _hat2;\n\t\t\thats[2] = _hat3;\n\t\t\thats[3] = _hat4;\n\t \t\n\t\t\tfor(int currentHatIndex = _hatSwitchCount -1 ; currentHatIndex >= 0 ; currentHatIndex--)\n\t\t\t{\n\t\t\t\tm[currentReportIndex++] = hats[currentHatIndex];\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis->inputGamepad->setValue(m, sizeof(m));\n\t\tthis->inputGamepad->notify();\n\t}\n}\n\nvoid BleGamepad::press(uint8_t b)\n{\n\n uint8_t index = (b-1) \/ 8;\n uint8_t bit = (b-1) % 8;\n uint8_t bitmask = (1 << bit);\n\n uint8_t result = _buttons[index] | bitmask;\n \n if (result != _buttons[index]) \n {\n _buttons[index] = result;\n }\n \n if(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::release(uint8_t b)\n{\n uint8_t index = (b-1) \/ 8;\n uint8_t bit = (b-1) % 8;\n uint8_t bitmask = (1 << bit);\n\n uint64_t result = _buttons[index] & ~bitmask;\n \n if (result != _buttons[index]) \n {\n _buttons[index] = result;\n }\n \n if(_autoReport){ sendReport(); }\n\n}\n\nvoid BleGamepad::setLeftThumb(int16_t x, int16_t y)\n{\n\tif(x == -32768) { x = -32767; }\n\tif(y == -32768) { y = -32767; }\n\t\n\t_x = x;\n\t_y = y;\n\t\n\tif(_autoReport){ sendReport(); }\n}\nvoid BleGamepad::setRightThumb(int16_t z, int16_t rZ)\n{\n\tif(z == -32768) { z = -32767; }\n\tif(rZ == -32768) { rZ = -32767; }\n\t\n\t_z = z;\n\t_rZ = rZ;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setLeftTrigger(int16_t rX)\n{\n\tif(rX == -32768) {rX = -32767; }\n\t\n\t_rX = rX;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setRightTrigger(int16_t rY)\n{\n\tif(rY == -32768) {rY = -32767; }\n\t\n\t_rY = rY;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setTriggers(int16_t rX, int16_t rY)\n{\n\tif(rX == -32768) {rX = -32767; }\n\tif(rY == -32768) {rY = -32767; }\n\t\n\t_rX = rX;\n\t_rY = rY;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setHat(signed char hat)\n{\n\t_hat1 = hat;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setHat1(signed char hat1)\n{\n\t_hat1 = hat1;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setHat2(signed char hat2)\n{\n\t_hat2 = hat2;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setHat3(signed char hat3)\n{\n\t_hat3 = hat3;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setHat4(signed char hat4)\n{\n\t_hat4 = hat4;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setX(int16_t x)\n{\n\tif(x == -32768) { x = -32767; }\n\n\t_x = x;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setY(int16_t y)\n{\n\tif(y == -32768) { y = -32767; }\n\t\n\t_y = y;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setZ(int16_t z)\n{\n\tif(z == -32768) { z = -32767; }\n\t\n\t_z = z;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setRZ(int16_t rZ)\n{\n\tif(rZ == -32768) { rZ = -32767; }\n\t\n\t_rZ = rZ;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setRX(int16_t rX)\n{\n\tif(rX == -32768) { rX = -32767; }\n\t\n\t_rX = rX;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setRY(int16_t rY)\n{\n\tif(rY == -32768) { rY = -32767; }\n\t\n\t_rY = rY;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setSlider(int16_t slider)\n{\n\tif(slider == -32768) { slider = -32767; }\n\t\n\t_slider1 = slider;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setSlider1(int16_t slider1)\n{\n\tif(slider1 == -32768) { slider1 = -32767; }\n\t\n\t_slider1 = slider1;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setSlider2(int16_t slider2)\n{\n\tif(slider2 == -32768) { slider2 = -32767; }\n\t\n\t_slider2 = slider2;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setRudder(int16_t rudder)\n{\n\tif(rudder == -32768) { rudder = -32767; }\n\t\n\t_rudder = rudder;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setThrottle(int16_t throttle)\n{\n\tif(throttle == -32768) { throttle = -32767; }\n\t\n\t_throttle = throttle;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setAccelerator(int16_t accelerator)\n{\n\tif(accelerator == -32768) { accelerator = -32767; }\n\t\n\t_accelerator = accelerator;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setBrake(int16_t brake)\n{\n\tif(brake == -32768) { brake = -32767; }\n\t\n\t_brake = brake;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setSteering(int16_t steering)\n{\n\tif(steering == -32768) { steering = -32767; }\n\t\n\t_steering = steering;\n\t\n\tif(_autoReport){ sendReport(); }\n}\n\nvoid BleGamepad::setAutoReport(bool autoReport)\n{\n\t_autoReport = autoReport;\n}\n\nbool BleGamepad::isPressed(uint8_t b)\n{\n uint8_t index = (b-1) \/ 8;\n uint8_t bit = (b-1) % 8;\n uint8_t bitmask = (1 << bit);\n\n if ((bitmask & _buttons[index]) > 0)\n return true;\n return false;\n}\n\nbool BleGamepad::isConnected(void) \n{\n return this->connectionStatus->connected;\n}\n\nvoid BleGamepad::setBatteryLevel(uint8_t level) \n{\n this->batteryLevel = level;\n if (hid != 0)\n this->hid->setBatteryLevel(this->batteryLevel);\n}\n\nvoid BleGamepad::taskServer(void* pvParameter) \n{\n BleGamepad* BleGamepadInstance = (BleGamepad *) pvParameter; \/\/static_cast(pvParameter);\n NimBLEDevice::init(BleGamepadInstance->deviceName);\n NimBLEServer *pServer = NimBLEDevice::createServer();\n pServer->setCallbacks(BleGamepadInstance->connectionStatus);\n\n BleGamepadInstance->hid = new NimBLEHIDDevice(pServer);\n BleGamepadInstance->inputGamepad = BleGamepadInstance->hid->inputReport(_hidReportId); \/\/ <-- input REPORTID from report map\n BleGamepadInstance->connectionStatus->inputGamepad = BleGamepadInstance->inputGamepad;\n\n BleGamepadInstance->hid->manufacturer()->setValue(BleGamepadInstance->deviceManufacturer);\n\n BleGamepadInstance->hid->pnp(0x01,0x02e5,0xabbb,0x0110);\n BleGamepadInstance->hid->hidInfo(0x00,0x01);\n\n NimBLESecurity *pSecurity = new NimBLESecurity();\n\n pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND);\n\n\n uint8_t *customHidReportDescriptor = new uint8_t[hidReportDescriptorSize];\n memcpy(customHidReportDescriptor, tempHidReportDescriptor, hidReportDescriptorSize);\n\n BleGamepadInstance->hid->reportMap((uint8_t*)customHidReportDescriptor, hidReportDescriptorSize);\n BleGamepadInstance->hid->startServices();\n\n BleGamepadInstance->onStarted(pServer);\n\n NimBLEAdvertising *pAdvertising = pServer->getAdvertising();\n pAdvertising->setAppearance(HID_GAMEPAD);\n pAdvertising->addServiceUUID(BleGamepadInstance->hid->hidService()->getUUID());\n pAdvertising->start();\n BleGamepadInstance->hid->setBatteryLevel(BleGamepadInstance->batteryLevel);\n\n ESP_LOGD(LOG_TAG, \"Advertising started!\");\n vTaskDelay(portMAX_DELAY); \/\/delay(portMAX_DELAY);\n}\n","avg_line_length":27.5470588235,"max_line_length":335,"alphanum_fraction":0.7150971599} {"size":1171,"ext":"cpp","lang":"C++","max_stars_count":427.0,"content":"\/\/===--- ImageInspectionInit.cpp ------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ This file along with swift_sections.S is prepended to each shared library on\n\/\/\/ an ELF target which contains protocol and metadata sections.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#if defined(__ELF__) || defined(__ANDROID__)\n\n#include \"ImageInspection.h\"\n#include \n\n\/\/ This is called at startup and by each shared object as it is dlopen()'d to\n\/\/ allow the section data for the object to be loaded.\n__attribute__((constructor))\nstatic void sectionDataInit() {\n void *addr = reinterpret_cast(std::addressof(sectionDataInit));\n swift_addNewDSOImage(addr);\n}\n\n#endif\n","avg_line_length":34.4411764706,"max_line_length":80,"alphanum_fraction":0.6046114432} {"size":2441,"ext":"cpp","lang":"C++","max_stars_count":5.0,"content":"\/*\n * Warhammer Age of Sigmar battle simulator.\n *\n * Copyright (C) 2020 by Rick Weyrauch - rpweyrauch@gmail.com\n *\n * This code is licensed under the MIT license (MIT) (http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include \n#include \"nurgle\/TheWurmspat.h\"\n#include \"NurglePrivate.h\"\n\nnamespace Nurgle {\n static const int g_basesize = 40;\n static const int g_wounds = 4;\n static const int g_pointsPerUnit = 0;\n\n bool TheWurmspat::s_registered = false;\n\n Unit *TheWurmspat::Create(const ParameterList ¶meters) {\n auto legion = (PlagueLegion) GetEnumParam(\"Plague Legion\", parameters, (int) PlagueLegion::None);\n return new TheWurmspat(legion);\n }\n\n void TheWurmspat::Init() {\n if (!s_registered) {\n static FactoryMethod factoryMethod = {\n TheWurmspat::Create,\n NurgleBase::ValueToString,\n NurgleBase::EnumStringToInt,\n TheWurmspat::ComputePoints,\n {\n EnumParameter(\"Plague Legion\", g_plagueLegions[0], g_plagueLegions),\n },\n CHAOS,\n {NURGLE}\n };\n s_registered = UnitFactory::Register(\"The Wurmspat\", factoryMethod);\n }\n }\n\n TheWurmspat::TheWurmspat(PlagueLegion legion) :\n NurgleBase(legion, \"The Wurmspat\", 4, g_wounds, 8, 4, false, g_pointsPerUnit),\n m_blightedWeapons(Weapon::Type::Melee, \"Blighted Weapon\", 1, 3, 3, 3, 0, 1) {\n m_keywords = {CHAOS, MORTAL, NURGLE, ROTBRINGER, BLESSED_SONS, PUTRID_BLIGHTKINGS, THE_WURMSPAT};\n m_weapons = {&m_blightedWeapons};\n\n auto sepsimus = new Model(g_basesize, wounds());\n sepsimus->addMeleeWeapon(&m_blightedWeapons);\n addModel(sepsimus);\n\n auto ghulgoch = new Model(g_basesize, wounds());\n ghulgoch->addMeleeWeapon(&m_blightedWeapons);\n addModel(ghulgoch);\n }\n\n int TheWurmspat::generateHits(int unmodifiedHitRoll, const Weapon *weapon, const Unit *unit) const {\n \/\/ Blighted Weapons\n if (unmodifiedHitRoll == 6) {\n \/\/ each 6 inflicts D6 hits\n return Dice::RollD6();\n }\n\n return NurgleBase::generateHits(unmodifiedHitRoll, weapon, unit);\n }\n\n int TheWurmspat::ComputePoints(const ParameterList& \/*parameters*\/) {\n return g_pointsPerUnit;\n }\n\n} \/\/ namespace Nurgle\n","avg_line_length":33.9027777778,"max_line_length":105,"alphanum_fraction":0.614092585} {"size":276,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n#include \n#include \n#include \nusing namespace std;\nint main() {\n string s, t, u; cin >> s >> t >> u;\n if (s.length() == 5 && t.length() == 7 && u.length() == 5) cout << \"valid\" << endl;\n else cout << \"invalid\" << endl;\n}\n","avg_line_length":25.0909090909,"max_line_length":87,"alphanum_fraction":0.5543478261} {"size":10121,"ext":"cpp","lang":"C++","max_stars_count":1433.0,"content":"\/\/******************************************************************\n\/\/\n\/\/ Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ocstack.h\"\n#include \"logger.h\"\n#include \"occlientslow.h\"\n#include \"oic_string.h\"\n#include \"ocpayload.h\"\n#include \"payload_logging.h\"\n\n\/\/ Tracking user input\nstatic int UnicastDiscovery = 0;\nstatic int TestCase = 0;\nstatic int ConnectivityType = 0;\n\nstatic std::string coapServerResource = \"\/a\/led\";\n\n\/\/The following variable determines the interface protocol (IP, etc)\n\/\/to be used for sending unicast messages. Default set to IP.\nstatic OCConnectivityType AdapterType = CT_ADAPTER_IP;\nstatic OCDevAddr endpoint;\nstatic const char *RESOURCE_DISCOVERY_QUERY = \"%s\/oic\/res\";\nvoid StripNewLineChar(char* str);\n\nint gQuitFlag = 0;\n\n\/* SIGINT handler: set gQuitFlag to 1 for graceful termination *\/\nvoid handleSigInt(int signum)\n{\n if (signum == SIGINT)\n {\n gQuitFlag = 1;\n }\n}\n\nstatic void PrintUsage()\n{\n OC_LOG(INFO, TAG, \"Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>\");\n OC_LOG(INFO, TAG, \"-c 0 : Default auto-selection\");\n OC_LOG(INFO, TAG, \"-c 1 : IP Connectivity Type\");\n OC_LOG(INFO, TAG, \"-u <0|1> : Perform multicast\/unicast discovery of resources\");\n OC_LOG(INFO, TAG, \"-t 1 : Discover Resources\");\n OC_LOG(INFO, TAG, \"-t 2 : Discover Resources and Initiate Nonconfirmable Get Request\");\n OC_LOG(INFO, TAG, \"-t 3 : Discover Resources and Initiate Confirmable Get Request\");\n OC_LOG(INFO, TAG, \"-t 4 : Discover Resources and Initiate NonConfirmable Put Request\");\n OC_LOG(INFO, TAG, \"-t 5 : Discover Resources and Initiate Confirmable Put Request\");\n}\n\nOCPayload* putPayload()\n{\n OCRepPayload* payload = OCRepPayloadCreate();\n\n if(!payload)\n {\n std::cout << \"Failed to create put payload object\"<result));\n OC_LOG_V(INFO, TAG, \"SEQUENCE NUMBER: %d\", clientResponse->sequenceNumber);\n OC_LOG(INFO, TAG, \"Get Response =============> \");\n OC_LOG_PAYLOAD(INFO, clientResponse->payload);\n\n if(clientResponse->rcvdVendorSpecificHeaderOptions &&\n clientResponse->numRcvdVendorSpecificHeaderOptions)\n {\n OC_LOG (INFO, TAG, \"Received vendor specific options\");\n uint8_t i = 0;\n OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;\n for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)\n {\n if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)\n {\n OC_LOG_V(INFO, TAG, \"Received option with OC_COAP_ID and ID %u with\",\n ((OCHeaderOption)rcvdOptions[i]).optionID );\n\n OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,\n MAX_HEADER_OPTION_DATA_LENGTH);\n }\n }\n }\n return OC_STACK_DELETE_TRANSACTION;\n}\n\n\/\/ This is a function called back when a device is discovered\nOCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle \/*handle*\/,\n OCClientResponse * clientResponse)\n{\n if (ctx == (void*) DEFAULT_CONTEXT_VALUE)\n {\n OC_LOG(INFO, TAG, \"Callback Context for DISCOVER query recvd successfully\");\n }\n\n if (clientResponse)\n {\n OC_LOG_V(INFO, TAG, \"StackResult: %s\", getResult(clientResponse->result));\n\n OC_LOG_V(INFO, TAG, \"Discovered @ %s:%u =============> \",\n clientResponse->devAddr.addr, clientResponse->devAddr.port);\n OC_LOG_PAYLOAD (INFO, clientResponse->payload);\n\n endpoint = clientResponse->devAddr;\n\n switch(TestCase)\n {\n case TEST_NON_CON_OP:\n InitGetRequest(OC_LOW_QOS);\n break;\n case TEST_CON_OP:\n InitGetRequest(OC_HIGH_QOS);\n break;\n case TEST_NON_CON_PUT:\n InitPutRequest(OC_LOW_QOS);\n break;\n case TEST_CON_PUT:\n InitPutRequest(OC_HIGH_QOS);\n break;\n default:\n PrintUsage();\n break;\n }\n }\n\n return UnicastDiscovery ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;\n\n}\n\nint InitGetRequest(OCQualityOfService qos)\n{\n OC_LOG_V(INFO, TAG, \"\\n\\nExecuting %s\", __func__);\n std::ostringstream query;\n query << coapServerResource;\n OC_LOG_V (INFO, TAG, \"Performing GET with query : %s\", query.str().c_str());\n return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,\n (qos == OC_HIGH_QOS)? OC_HIGH_QOS : OC_LOW_QOS,\n getReqCB, NULL, 0));\n}\n\nint InitPutRequest(OCQualityOfService qos)\n{\n OC_LOG_V(INFO, TAG, \"\\n\\nExecuting %s\", __func__);\n std::ostringstream query;\n query << coapServerResource;\n OC_LOG_V (INFO, TAG, \"Performing PUT with query : %s\", query.str().c_str());\n return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,\n (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,\n getReqCB, NULL, 0));\n}\n\nint InitDiscovery()\n{\n OCStackResult ret;\n OCCallbackData cbData;\n char queryUri[200];\n char ipaddr[100] = { '\\0' };\n\n if (UnicastDiscovery)\n {\n OC_LOG(INFO, TAG, \"Enter IP address (with optional port) of the Server hosting resource\\n\");\n OC_LOG(INFO, TAG, \"IPv4: 192.168.0.15:45454\\n\");\n OC_LOG(INFO, TAG, \"IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\\n\");\n\n if (fgets(ipaddr, sizeof (ipaddr), stdin))\n {\n StripNewLineChar(ipaddr); \/\/Strip newline char from ipaddr\n }\n else\n {\n OC_LOG(ERROR, TAG, \"!! Bad input for IP address. !!\");\n return OC_STACK_INVALID_PARAM;\n }\n }\n\n snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);\n\n cbData.cb = discoveryReqCB;\n cbData.context = (void*)DEFAULT_CONTEXT_VALUE;\n cbData.cd = NULL;\n\n ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,\n OC_LOW_QOS, &cbData, NULL, 0);\n if (ret != OC_STACK_OK)\n {\n OC_LOG(ERROR, TAG, \"OCStack resource error\");\n }\n return ret;\n}\n\nint main(int argc, char* argv[])\n{\n int opt;\n\n while ((opt = getopt(argc, argv, \"u:t:c:\")) != -1)\n {\n switch(opt)\n {\n case 'u':\n UnicastDiscovery = atoi(optarg);\n break;\n case 't':\n TestCase = atoi(optarg);\n break;\n case 'c':\n ConnectivityType = atoi(optarg);\n break;\n default:\n PrintUsage();\n return -1;\n }\n }\n\n if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||\n (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||\n (ConnectivityType < CT_ADAPTER_DEFAULT || ConnectivityType >= MAX_CT))\n {\n PrintUsage();\n return -1;\n }\n\n \/* Initialize OCStack*\/\n if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)\n {\n OC_LOG(ERROR, TAG, \"OCStack init error\");\n return 0;\n }\n\n if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)\n {\n AdapterType = CT_ADAPTER_IP;\n }\n else\n {\n OC_LOG(INFO, TAG, \"Default Connectivity type selected...\");\n AdapterType = CT_ADAPTER_IP;\n }\n\n InitDiscovery();\n\n \/\/ Break from loop with Ctrl+C\n OC_LOG(INFO, TAG, \"Entering occlient main loop...\");\n signal(SIGINT, handleSigInt);\n while (!gQuitFlag)\n {\n if (OCProcess() != OC_STACK_OK)\n {\n OC_LOG(ERROR, TAG, \"OCStack process error\");\n return 0;\n }\n\n sleep(2);\n }\n OC_LOG(INFO, TAG, \"Exiting occlient main loop...\");\n\n if (OCStop() != OC_STACK_OK)\n {\n OC_LOG(ERROR, TAG, \"OCStack stop error\");\n }\n\n return 0;\n}\n\nstd::string getQueryStrForGetPut(OCClientResponse * \/*clientResponse*\/)\n{\n return \"\/a\/led\";\n}\n\n","avg_line_length":30.3933933934,"max_line_length":100,"alphanum_fraction":0.603892896} {"size":43727,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/***********************************************************************\n**********Copyright (c) 2014-2015 The Dash Core developers**************\n*************Copyright (c) 2015-2017 The PIVX developers****************\n******************Copyright (c) 2010-2019 Nur1Labs**********************\n>Distributed under the MIT\/X11 software license, see the accompanying\n>file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n************************************************************************\/\n\n#include \"masternodeman.h\"\n#include \"activemasternode.h\"\n#include \"addrman.h\"\n#include \"masternode.h\"\n#include \"obfuscation.h\"\n#include \"spork.h\"\n#include \"util.h\"\n#include \n#include \n\n#define MN_WINNER_MINIMUM_AGE 8000 \/\/ Age in seconds. This should be > MASTERNODE_REMOVAL_SECONDS to avoid misconfigured new nodes in the list.\n\n\/** Masternode manager *\/\nCMasternodeMan mnodeman;\n\nstruct CompareLastPaid {\n bool operator()(const pair& t1,\n const pair& t2) const\n {\n return t1.first < t2.first;\n }\n};\n\nstruct CompareScoreTxIn {\n bool operator()(const pair& t1,\n const pair& t2) const\n {\n return t1.first < t2.first;\n }\n};\n\nstruct CompareScoreMN {\n bool operator()(const pair& t1,\n const pair& t2) const\n {\n return t1.first < t2.first;\n }\n};\n\n\/\/\n\/\/ CMasternodeDB\n\/\/\n\nCMasternodeDB::CMasternodeDB()\n{\n pathMN = GetDataDir() \/ \"mncache.dat\";\n strMagicMessage = \"MasternodeCache\";\n}\n\nbool CMasternodeDB::Write(const CMasternodeMan& mnodemanToSave)\n{\n int64_t nStart = GetTimeMillis();\n\n \/\/ serialize, checksum data up to that point, then append checksum\n CDataStream ssMasternodes(SER_DISK, CLIENT_VERSION);\n ssMasternodes << strMagicMessage; \/\/ masternode cache file specific magic message\n ssMasternodes << FLATDATA(Params().MessageStart()); \/\/ network specific magic number\n ssMasternodes << mnodemanToSave;\n uint256 hash = Hash(ssMasternodes.begin(), ssMasternodes.end());\n ssMasternodes << hash;\n\n \/\/ open output file, and associate with CAutoFile\n FILE* file = fopen(pathMN.string().c_str(), \"wb\");\n CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);\n if (fileout.IsNull())\n return error(\"%s : Failed to open file %s\", __func__, pathMN.string());\n\n \/\/ Write and commit header, data\n try {\n fileout << ssMasternodes;\n } catch (std::exception& e) {\n return error(\"%s : Serialize or I\/O error - %s\", __func__, e.what());\n }\n \/\/ FileCommit(fileout);\n fileout.fclose();\n\n LogPrint(\"masternode\",\"Written info to mncache.dat %dms\\n\", GetTimeMillis() - nStart);\n LogPrint(\"masternode\",\" %s\\n\", mnodemanToSave.ToString());\n\n return true;\n}\n\nCMasternodeDB::ReadResult CMasternodeDB::Read(CMasternodeMan& mnodemanToLoad, bool fDryRun)\n{\n int64_t nStart = GetTimeMillis();\n \/\/ open input file, and associate with CAutoFile\n FILE* file = fopen(pathMN.string().c_str(), \"rb\");\n CAutoFile filein(file, SER_DISK, CLIENT_VERSION);\n if (filein.IsNull()) {\n error(\"%s : Failed to open file %s\", __func__, pathMN.string());\n return FileError;\n }\n\n \/\/ use file size to size memory buffer\n int fileSize = boost::filesystem::file_size(pathMN);\n int dataSize = fileSize - sizeof(uint256);\n \/\/ Don't try to resize to a negative number if file is small\n if (dataSize < 0)\n dataSize = 0;\n vector vchData;\n vchData.resize(dataSize);\n uint256 hashIn;\n\n \/\/ read data and checksum from file\n try {\n filein.read((char*)&vchData[0], dataSize);\n filein >> hashIn;\n } catch (std::exception& e) {\n error(\"%s : Deserialize or I\/O error - %s\", __func__, e.what());\n return HashReadError;\n }\n filein.fclose();\n\n CDataStream ssMasternodes(vchData, SER_DISK, CLIENT_VERSION);\n\n \/\/ verify stored checksum matches input data\n uint256 hashTmp = Hash(ssMasternodes.begin(), ssMasternodes.end());\n if (hashIn != hashTmp) {\n error(\"%s : Checksum mismatch, data corrupted\", __func__);\n return IncorrectHash;\n }\n\n unsigned char pchMsgTmp[4];\n std::string strMagicMessageTmp;\n try {\n \/\/ de-serialize file header (masternode cache file specific magic message) and ..\n\n ssMasternodes >> strMagicMessageTmp;\n\n \/\/ ... verify the message matches predefined one\n if (strMagicMessage != strMagicMessageTmp) {\n error(\"%s : Invalid masternode cache magic message\", __func__);\n return IncorrectMagicMessage;\n }\n\n \/\/ de-serialize file header (network specific magic number) and ..\n ssMasternodes >> FLATDATA(pchMsgTmp);\n\n \/\/ ... verify the network matches ours\n if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {\n error(\"%s : Invalid network magic number\", __func__);\n return IncorrectMagicNumber;\n }\n \/\/ de-serialize data into CMasternodeMan object\n ssMasternodes >> mnodemanToLoad;\n } catch (std::exception& e) {\n mnodemanToLoad.Clear();\n error(\"%s : Deserialize or I\/O error - %s\", __func__, e.what());\n return IncorrectFormat;\n }\n\n LogPrint(\"masternode\",\"Loaded info from mncache.dat %dms\\n\", GetTimeMillis() - nStart);\n LogPrint(\"masternode\",\" %s\\n\", mnodemanToLoad.ToString());\n if (!fDryRun) {\n LogPrint(\"masternode\",\"Masternode manager - cleaning....\\n\");\n mnodemanToLoad.CheckAndRemove(true);\n LogPrint(\"masternode\",\"Masternode manager - result:\\n\");\n LogPrint(\"masternode\",\" %s\\n\", mnodemanToLoad.ToString());\n }\n\n return Ok;\n}\n\nvoid DumpMasternodes()\n{\n int64_t nStart = GetTimeMillis();\n\n CMasternodeDB mndb;\n CMasternodeMan tempMnodeman;\n\n LogPrint(\"masternode\",\"Verifying mncache.dat format...\\n\");\n CMasternodeDB::ReadResult readResult = mndb.Read(tempMnodeman, true);\n \/\/ there was an error and it was not an error on file opening => do not proceed\n if (readResult == CMasternodeDB::FileError)\n LogPrint(\"masternode\",\"Missing masternode cache file - mncache.dat, will try to recreate\\n\");\n else if (readResult != CMasternodeDB::Ok) {\n LogPrint(\"masternode\",\"Error reading mncache.dat: \");\n if (readResult == CMasternodeDB::IncorrectFormat)\n LogPrint(\"masternode\",\"magic is ok but data has invalid format, will try to recreate\\n\");\n else {\n LogPrint(\"masternode\",\"file format is unknown or invalid, please fix it manually\\n\");\n return;\n }\n }\n LogPrint(\"masternode\",\"Writting info to mncache.dat...\\n\");\n mndb.Write(mnodeman);\n\n LogPrint(\"masternode\",\"Masternode dump finished %dms\\n\", GetTimeMillis() - nStart);\n}\n\nCMasternodeMan::CMasternodeMan()\n{\n nDsqCount = 0;\n}\n\nbool CMasternodeMan::Add(CMasternode& mn)\n{\n LOCK(cs);\n\n if (!mn.IsEnabled())\n return false;\n\n CMasternode* pmn = Find(mn.vin);\n if (pmn == NULL) {\n LogPrint(\"masternode\", \"CMasternodeMan: Adding new Masternode %s - %i now\\n\", mn.vin.prevout.hash.ToString(), size() + 1);\n vMasternodes.push_back(mn);\n return true;\n }\n\n return false;\n}\n\nvoid CMasternodeMan::AskForMN(CNode* pnode, CTxIn& vin)\n{\n std::map::iterator i = mWeAskedForMasternodeListEntry.find(vin.prevout);\n if (i != mWeAskedForMasternodeListEntry.end()) {\n int64_t t = (*i).second;\n if (GetTime() < t) return; \/\/ we've asked recently\n }\n\n \/\/ ask for the mnb info once from the node that sent mnp\n\n LogPrint(\"masternode\", \"CMasternodeMan::AskForMN - Asking node for missing entry, vin: %s\\n\", vin.prevout.hash.ToString());\n pnode->PushMessage(\"dseg\", vin);\n int64_t askAgain = GetTime() + MASTERNODE_MIN_MNP_SECONDS;\n mWeAskedForMasternodeListEntry[vin.prevout] = askAgain;\n}\n\nvoid CMasternodeMan::Check()\n{\n LOCK(cs);\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n mn.Check();\n }\n}\n\nvoid CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval)\n{\n Check();\n\n LOCK(cs);\n\n \/\/remove inactive and outdated\n vector::iterator it = vMasternodes.begin();\n while (it != vMasternodes.end()) {\n if ((*it).activeState == CMasternode::MASTERNODE_REMOVE ||\n (*it).activeState == CMasternode::MASTERNODE_VIN_SPENT ||\n (forceExpiredRemoval && (*it).activeState == CMasternode::MASTERNODE_EXPIRED) ||\n (*it).protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) {\n LogPrint(\"masternode\", \"CMasternodeMan: Removing inactive Masternode %s - %i now\\n\", (*it).vin.prevout.hash.ToString(), size() - 1);\n\n \/\/erase all of the broadcasts we've seen from this vin\n \/\/ -- if we missed a few pings and the node was removed, this will allow is to get it back without them\n \/\/ sending a brand new mnb\n map::iterator it3 = mapSeenMasternodeBroadcast.begin();\n while (it3 != mapSeenMasternodeBroadcast.end()) {\n if ((*it3).second.vin == (*it).vin) {\n masternodeSync.mapSeenSyncMNB.erase((*it3).first);\n mapSeenMasternodeBroadcast.erase(it3++);\n } else {\n ++it3;\n }\n }\n\n \/\/ allow us to ask for this masternode again if we see another ping\n map::iterator it2 = mWeAskedForMasternodeListEntry.begin();\n while (it2 != mWeAskedForMasternodeListEntry.end()) {\n if ((*it2).first == (*it).vin.prevout) {\n mWeAskedForMasternodeListEntry.erase(it2++);\n } else {\n ++it2;\n }\n }\n\n it = vMasternodes.erase(it);\n } else {\n ++it;\n }\n }\n\n \/\/ check who's asked for the Masternode list\n map::iterator it1 = mAskedUsForMasternodeList.begin();\n while (it1 != mAskedUsForMasternodeList.end()) {\n if ((*it1).second < GetTime()) {\n mAskedUsForMasternodeList.erase(it1++);\n } else {\n ++it1;\n }\n }\n\n \/\/ check who we asked for the Masternode list\n it1 = mWeAskedForMasternodeList.begin();\n while (it1 != mWeAskedForMasternodeList.end()) {\n if ((*it1).second < GetTime()) {\n mWeAskedForMasternodeList.erase(it1++);\n } else {\n ++it1;\n }\n }\n\n \/\/ check which Masternodes we've asked for\n map::iterator it2 = mWeAskedForMasternodeListEntry.begin();\n while (it2 != mWeAskedForMasternodeListEntry.end()) {\n if ((*it2).second < GetTime()) {\n mWeAskedForMasternodeListEntry.erase(it2++);\n } else {\n ++it2;\n }\n }\n\n \/\/ remove expired mapSeenMasternodeBroadcast\n map::iterator it3 = mapSeenMasternodeBroadcast.begin();\n while (it3 != mapSeenMasternodeBroadcast.end()) {\n if ((*it3).second.lastPing.sigTime < GetTime() - (MASTERNODE_REMOVAL_SECONDS * 2)) {\n mapSeenMasternodeBroadcast.erase(it3++);\n masternodeSync.mapSeenSyncMNB.erase((*it3).second.GetHash());\n } else {\n ++it3;\n }\n }\n\n \/\/ remove expired mapSeenMasternodePing\n map::iterator it4 = mapSeenMasternodePing.begin();\n while (it4 != mapSeenMasternodePing.end()) {\n if ((*it4).second.sigTime < GetTime() - (MASTERNODE_REMOVAL_SECONDS * 2)) {\n mapSeenMasternodePing.erase(it4++);\n } else {\n ++it4;\n }\n }\n}\n\nvoid CMasternodeMan::Clear()\n{\n LOCK(cs);\n vMasternodes.clear();\n mAskedUsForMasternodeList.clear();\n mWeAskedForMasternodeList.clear();\n mWeAskedForMasternodeListEntry.clear();\n mapSeenMasternodeBroadcast.clear();\n mapSeenMasternodePing.clear();\n nDsqCount = 0;\n}\n\nint CMasternodeMan::stable_size ()\n{\n int nStable_size = 0;\n int nMinProtocol = ActiveProtocol();\n int64_t nMasternode_Min_Age = MN_WINNER_MINIMUM_AGE;\n int64_t nMasternode_Age = 0;\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n if (mn.protocolVersion < nMinProtocol) {\n continue; \/\/ Skip obsolete versions\n }\n if (IsSporkActive (SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {\n nMasternode_Age = GetAdjustedTime() - mn.sigTime;\n if ((nMasternode_Age) < nMasternode_Min_Age) {\n continue; \/\/ Skip masternodes younger than (default) 8000 sec (MUST be > MASTERNODE_REMOVAL_SECONDS)\n }\n }\n mn.Check ();\n if (!mn.IsEnabled ())\n continue; \/\/ Skip not-enabled masternodes\n\n nStable_size++;\n }\n\n return nStable_size;\n}\n\nint CMasternodeMan::CountEnabled(int protocolVersion)\n{\n int i = 0;\n protocolVersion = protocolVersion == -1 ? masternodePayments.GetMinMasternodePaymentsProto() : protocolVersion;\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n mn.Check();\n if (mn.protocolVersion < protocolVersion || !mn.IsEnabled()) continue;\n i++;\n }\n\n return i;\n}\n\nvoid CMasternodeMan::CountNetworks(int protocolVersion, int& ipv4, int& ipv6, int& onion)\n{\n protocolVersion = protocolVersion == -1 ? masternodePayments.GetMinMasternodePaymentsProto() : protocolVersion;\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n mn.Check();\n std::string strHost;\n int port;\n SplitHostPort(mn.addr.ToString(), port, strHost);\n CNetAddr node = CNetAddr(strHost, false);\n int nNetwork = node.GetNetwork();\n switch (nNetwork) {\n case 1 :\n ipv4++;\n break;\n case 2 :\n ipv6++;\n break;\n case 3 :\n onion++;\n break;\n }\n }\n}\n\nvoid CMasternodeMan::DsegUpdate(CNode* pnode)\n{\n LOCK(cs);\n\n if (Params().NetworkID() == CBaseChainParams::MAIN) {\n if (!(pnode->addr.IsRFC1918() || pnode->addr.IsLocal())) {\n std::map::iterator it = mWeAskedForMasternodeList.find(pnode->addr);\n if (it != mWeAskedForMasternodeList.end()) {\n if (GetTime() < (*it).second) {\n LogPrint(\"masternode\", \"dseg - we already asked peer %i for the list; skipping...\\n\", pnode->GetId());\n return;\n }\n }\n }\n }\n\n pnode->PushMessage(\"dseg\", CTxIn());\n int64_t askAgain = GetTime() + MASTERNODES_DSEG_SECONDS;\n mWeAskedForMasternodeList[pnode->addr] = askAgain;\n}\n\nCMasternode* CMasternodeMan::Find(const CScript& payee)\n{\n LOCK(cs);\n CScript payee2;\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n payee2 = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID());\n if (payee2 == payee)\n return &mn;\n }\n return NULL;\n}\n\nCMasternode* CMasternodeMan::Find(const CTxIn& vin)\n{\n LOCK(cs);\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n if (mn.vin.prevout == vin.prevout)\n return &mn;\n }\n return NULL;\n}\n\n\nCMasternode* CMasternodeMan::Find(const CPubKey& pubKeyMasternode)\n{\n LOCK(cs);\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n if (mn.pubKeyMasternode == pubKeyMasternode)\n return &mn;\n }\n return NULL;\n}\n\n\/\/\n\/\/ Deterministically select the oldest\/best masternode to pay on the network\n\/\/\nCMasternode* CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool fFilterSigTime, int& nCount)\n{\n LOCK(cs);\n\n CMasternode* pBestMasternode = NULL;\n std::vector > vecMasternodeLastPaid;\n\n \/*\n Make a vector with all of the last paid times\n *\/\n\n int nMnCount = CountEnabled();\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n mn.Check();\n if (!mn.IsEnabled()) continue;\n\n \/\/ \/\/check protocol version\n if (mn.protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) continue;\n\n \/\/it's in the list (up to 8 entries ahead of current block to allow propagation) -- so let's skip it\n if (masternodePayments.IsScheduled(mn, nBlockHeight)) continue;\n\n \/\/it's too new, wait for a cycle\n if (fFilterSigTime && mn.sigTime + (nMnCount * 2.6 * 60) > GetAdjustedTime()) continue;\n\n \/\/make sure it has as many confirmations as there are masternodes\n if (mn.GetMasternodeInputAge() < nMnCount) continue;\n\n vecMasternodeLastPaid.push_back(make_pair(mn.SecondsSincePayment(), mn.vin));\n }\n\n nCount = (int)vecMasternodeLastPaid.size();\n\n \/\/when the network is in the process of upgrading, don't penalize nodes that recently restarted\n if (fFilterSigTime && nCount < nMnCount \/ 3) return GetNextMasternodeInQueueForPayment(nBlockHeight, false, nCount);\n\n \/\/ Sort them high to low\n sort(vecMasternodeLastPaid.rbegin(), vecMasternodeLastPaid.rend(), CompareLastPaid());\n\n \/\/ Look at 1\/10 of the oldest nodes (by last payment), calculate their scores and pay the best one\n \/\/ -- This doesn't look at who is being paid in the +8-10 blocks, allowing for double payments very rarely\n \/\/ -- 1\/100 payments should be a double payment on mainnet - (1\/(3000\/10))*2\n \/\/ -- (chance per block * chances before IsScheduled will fire)\n int nTenthNetwork = CountEnabled() \/ 10;\n int nCountTenth = 0;\n uint256 nHigh = 0;\n BOOST_FOREACH (PAIRTYPE(int64_t, CTxIn) & s, vecMasternodeLastPaid) {\n CMasternode* pmn = Find(s.second);\n if (!pmn) break;\n\n uint256 n = pmn->CalculateScore(1, nBlockHeight - 100);\n if (n > nHigh) {\n nHigh = n;\n pBestMasternode = pmn;\n }\n nCountTenth++;\n if (nCountTenth >= nTenthNetwork) break;\n }\n return pBestMasternode;\n}\n\nCMasternode* CMasternodeMan::FindRandomNotInVec(std::vector& vecToExclude, int protocolVersion)\n{\n LOCK(cs);\n\n protocolVersion = protocolVersion == -1 ? masternodePayments.GetMinMasternodePaymentsProto() : protocolVersion;\n\n int nCountEnabled = CountEnabled(protocolVersion);\n LogPrint(\"masternode\", \"CMasternodeMan::FindRandomNotInVec - nCountEnabled - vecToExclude.size() %d\\n\", nCountEnabled - vecToExclude.size());\n if (nCountEnabled - vecToExclude.size() < 1) return NULL;\n\n int rand = GetRandInt(nCountEnabled - vecToExclude.size());\n LogPrint(\"masternode\", \"CMasternodeMan::FindRandomNotInVec - rand %d\\n\", rand);\n bool found;\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n if (mn.protocolVersion < protocolVersion || !mn.IsEnabled()) continue;\n found = false;\n BOOST_FOREACH (CTxIn& usedVin, vecToExclude) {\n if (mn.vin.prevout == usedVin.prevout) {\n found = true;\n break;\n }\n }\n if (found) continue;\n if (--rand < 1) {\n return &mn;\n }\n }\n\n return NULL;\n}\n\nCMasternode* CMasternodeMan::GetCurrentMasterNode(int mod, int64_t nBlockHeight, int minProtocol)\n{\n int64_t score = 0;\n CMasternode* winner = NULL;\n\n \/\/ scan for winner\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n mn.Check();\n if (mn.protocolVersion < minProtocol || !mn.IsEnabled()) continue;\n\n \/\/ calculate the score for each Masternode\n uint256 n = mn.CalculateScore(mod, nBlockHeight);\n int64_t n2 = n.GetCompact(false);\n\n \/\/ determine the winner\n if (n2 > score) {\n score = n2;\n winner = &mn;\n }\n }\n\n return winner;\n}\n\nint CMasternodeMan::GetMasternodeRank(const CTxIn& vin, int64_t nBlockHeight, int minProtocol, bool fOnlyActive)\n{\n std::vector > vecMasternodeScores;\n int64_t nMasternode_Min_Age = MN_WINNER_MINIMUM_AGE;\n int64_t nMasternode_Age = 0;\n\n \/\/make sure we know about this block\n uint256 hash = 0;\n if (!GetBlockHash(hash, nBlockHeight)) return -1;\n\n \/\/ scan for winner\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n if (mn.protocolVersion < minProtocol) {\n LogPrint(\"masternode\",\"Skipping Masternode with obsolete version %d\\n\", mn.protocolVersion);\n continue; \/\/ Skip obsolete versions\n }\n\n if (IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {\n nMasternode_Age = GetAdjustedTime() - mn.sigTime;\n if ((nMasternode_Age) < nMasternode_Min_Age) {\n if (fDebug) LogPrint(\"masternode\",\"Skipping just activated Masternode. Age: %ld\\n\", nMasternode_Age);\n continue; \/\/ Skip masternodes younger than (default) 1 hour\n }\n }\n if (fOnlyActive) {\n mn.Check();\n if (!mn.IsEnabled()) continue;\n }\n uint256 n = mn.CalculateScore(1, nBlockHeight);\n int64_t n2 = n.GetCompact(false);\n\n vecMasternodeScores.push_back(make_pair(n2, mn.vin));\n }\n\n sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreTxIn());\n\n int rank = 0;\n BOOST_FOREACH (PAIRTYPE(int64_t, CTxIn) & s, vecMasternodeScores) {\n rank++;\n if (s.second.prevout == vin.prevout) {\n return rank;\n }\n }\n\n return -1;\n}\n\nstd::vector > CMasternodeMan::GetMasternodeRanks(int64_t nBlockHeight, int minProtocol)\n{\n std::vector > vecMasternodeScores;\n std::vector > vecMasternodeRanks;\n\n \/\/make sure we know about this block\n uint256 hash = 0;\n if (!GetBlockHash(hash, nBlockHeight)) return vecMasternodeRanks;\n\n \/\/ scan for winner\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n mn.Check();\n\n if (mn.protocolVersion < minProtocol) continue;\n\n if (!mn.IsEnabled()) {\n vecMasternodeScores.push_back(make_pair(9999, mn));\n continue;\n }\n\n uint256 n = mn.CalculateScore(1, nBlockHeight);\n int64_t n2 = n.GetCompact(false);\n\n vecMasternodeScores.push_back(make_pair(n2, mn));\n }\n\n sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreMN());\n\n int rank = 0;\n BOOST_FOREACH (PAIRTYPE(int64_t, CMasternode) & s, vecMasternodeScores) {\n rank++;\n vecMasternodeRanks.push_back(make_pair(rank, s.second));\n }\n\n return vecMasternodeRanks;\n}\n\nCMasternode* CMasternodeMan::GetMasternodeByRank(int nRank, int64_t nBlockHeight, int minProtocol, bool fOnlyActive)\n{\n std::vector > vecMasternodeScores;\n\n \/\/ scan for winner\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n if (mn.protocolVersion < minProtocol) continue;\n if (fOnlyActive) {\n mn.Check();\n if (!mn.IsEnabled()) continue;\n }\n\n uint256 n = mn.CalculateScore(1, nBlockHeight);\n int64_t n2 = n.GetCompact(false);\n\n vecMasternodeScores.push_back(make_pair(n2, mn.vin));\n }\n\n sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreTxIn());\n\n int rank = 0;\n BOOST_FOREACH (PAIRTYPE(int64_t, CTxIn) & s, vecMasternodeScores) {\n rank++;\n if (rank == nRank) {\n return Find(s.second);\n }\n }\n\n return NULL;\n}\n\nvoid CMasternodeMan::ProcessMasternodeConnections()\n{\n \/\/we don't care about this for regtest\n if (Params().NetworkID() == CBaseChainParams::REGTEST) return;\n\n LOCK(cs_vNodes);\n BOOST_FOREACH (CNode* pnode, vNodes) {\n if (pnode->fObfuScationMaster) {\n if (obfuScationPool.pSubmittedToMasternode != NULL && pnode->addr == obfuScationPool.pSubmittedToMasternode->addr) continue;\n LogPrint(\"masternode\",\"Closing Masternode connection peer=%i \\n\", pnode->GetId());\n pnode->fObfuScationMaster = false;\n pnode->Release();\n }\n }\n}\n\nvoid CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)\n{\n if (fLiteMode) return; \/\/disable all Obfuscation\/Masternode related functionality\n if (!masternodeSync.IsBlockchainSynced()) return;\n\n LOCK(cs_process_message);\n\n if (strCommand == \"mnb\") { \/\/Masternode Broadcast\n CMasternodeBroadcast mnb;\n vRecv >> mnb;\n\n if (mapSeenMasternodeBroadcast.count(mnb.GetHash())) { \/\/seen\n masternodeSync.AddedMasternodeList(mnb.GetHash());\n return;\n }\n mapSeenMasternodeBroadcast.insert(make_pair(mnb.GetHash(), mnb));\n\n int nDoS = 0;\n if (!mnb.CheckAndUpdate(nDoS)) {\n if (nDoS > 0)\n Misbehaving(pfrom->GetId(), nDoS);\n\n \/\/failed\n return;\n }\n\n \/\/ make sure the vout that was signed is related to the transaction that spawned the Masternode\n \/\/ - this is expensive, so it's only done once per Masternode\n if (!obfuScationSigner.IsVinAssociatedWithPubkey(mnb.vin, mnb.pubKeyCollateralAddress)) {\n LogPrint(\"masternode\",\"mnb - Got mismatched pubkey and vin\\n\");\n Misbehaving(pfrom->GetId(), 33);\n return;\n }\n\n \/\/ make sure it's still unspent\n \/\/ - this is checked later by .check() in many places and by ThreadCheckObfuScationPool()\n if (mnb.CheckInputsAndAdd(nDoS)) {\n \/\/ use this as a peer\n addrman.Add(CAddress(mnb.addr), pfrom->addr, 2 * 60 * 60);\n masternodeSync.AddedMasternodeList(mnb.GetHash());\n } else {\n LogPrint(\"masternode\",\"mnb - Rejected Masternode entry %s\\n\", mnb.vin.prevout.hash.ToString());\n\n if (nDoS > 0)\n Misbehaving(pfrom->GetId(), nDoS);\n }\n }\n\n else if (strCommand == \"mnp\") { \/\/Masternode Ping\n CMasternodePing mnp;\n vRecv >> mnp;\n\n LogPrint(\"masternode\", \"mnp - Masternode ping, vin: %s\\n\", mnp.vin.prevout.hash.ToString());\n\n if (mapSeenMasternodePing.count(mnp.GetHash())) return; \/\/seen\n mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp));\n\n int nDoS = 0;\n if (mnp.CheckAndUpdate(nDoS)) return;\n\n if (nDoS > 0) {\n \/\/ if anything significant failed, mark that node\n Misbehaving(pfrom->GetId(), nDoS);\n } else {\n \/\/ if nothing significant failed, search existing Masternode list\n CMasternode* pmn = Find(mnp.vin);\n \/\/ if it's known, don't ask for the mnb, just return\n if (pmn != NULL) return;\n }\n\n \/\/ something significant is broken or mn is unknown,\n \/\/ we might have to ask for a masternode entry once\n AskForMN(pfrom, mnp.vin);\n\n } else if (strCommand == \"dseg\") { \/\/Get Masternode list or specific entry\n\n CTxIn vin;\n vRecv >> vin;\n\n if (vin == CTxIn()) { \/\/only should ask for this once\n \/\/local network\n bool isLocal = (pfrom->addr.IsRFC1918() || pfrom->addr.IsLocal());\n\n if (!isLocal && Params().NetworkID() == CBaseChainParams::MAIN) {\n std::map::iterator i = mAskedUsForMasternodeList.find(pfrom->addr);\n if (i != mAskedUsForMasternodeList.end()) {\n int64_t t = (*i).second;\n if (GetTime() < t) {\n Misbehaving(pfrom->GetId(), 34);\n LogPrint(\"masternode\",\"dseg - peer already asked me for the list\\n\");\n return;\n }\n }\n int64_t askAgain = GetTime() + MASTERNODES_DSEG_SECONDS;\n mAskedUsForMasternodeList[pfrom->addr] = askAgain;\n }\n } \/\/else, asking for a specific node which is ok\n\n\n int nInvCount = 0;\n\n BOOST_FOREACH (CMasternode& mn, vMasternodes) {\n if (mn.addr.IsRFC1918()) continue; \/\/local network\n\n if (mn.IsEnabled()) {\n LogPrint(\"masternode\", \"dseg - Sending Masternode entry - %s \\n\", mn.vin.prevout.hash.ToString());\n if (vin == CTxIn() || vin == mn.vin) {\n CMasternodeBroadcast mnb = CMasternodeBroadcast(mn);\n uint256 hash = mnb.GetHash();\n pfrom->PushInventory(CInv(MSG_MASTERNODE_ANNOUNCE, hash));\n nInvCount++;\n\n if (!mapSeenMasternodeBroadcast.count(hash)) mapSeenMasternodeBroadcast.insert(make_pair(hash, mnb));\n\n if (vin == mn.vin) {\n LogPrint(\"masternode\", \"dseg - Sent 1 Masternode entry to peer %i\\n\", pfrom->GetId());\n return;\n }\n }\n }\n }\n\n if (vin == CTxIn()) {\n pfrom->PushMessage(\"ssc\", MASTERNODE_SYNC_LIST, nInvCount);\n LogPrint(\"masternode\", \"dseg - Sent %d Masternode entries to peer %i\\n\", nInvCount, pfrom->GetId());\n }\n }\n \/*\n * IT'S SAFE TO REMOVE THIS IN FURTHER VERSIONS\n * AFTER MIGRATION TO V12 IS DONE\n *\/\n\n \/\/ Light version for OLD MASSTERNODES - fake pings, no self-activation\n else if (strCommand == \"dsee\") { \/\/ObfuScation Election Entry\n\n if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return;\n\n CTxIn vin;\n CService addr;\n CPubKey pubkey;\n CPubKey pubkey2;\n vector vchSig;\n int64_t sigTime;\n int count;\n int current;\n int64_t lastUpdated;\n int protocolVersion;\n CScript donationAddress;\n int donationPercentage;\n std::string strMessage;\n\n vRecv >> vin >> addr >> vchSig >> sigTime >> pubkey >> pubkey2 >> count >> current >> lastUpdated >> protocolVersion >> donationAddress >> donationPercentage;\n\n \/\/ make sure signature isn't in the future (past is OK)\n if (sigTime > GetAdjustedTime() + 60 * 60) {\n LogPrint(\"masternode\",\"dsee - Signature rejected, too far into the future %s\\n\", vin.prevout.hash.ToString());\n Misbehaving(pfrom->GetId(), 1);\n return;\n }\n\n std::string vchPubKey(pubkey.begin(), pubkey.end());\n std::string vchPubKey2(pubkey2.begin(), pubkey2.end());\n\n strMessage = addr.ToString() + boost::lexical_cast(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast(protocolVersion) + donationAddress.ToString() + boost::lexical_cast(donationPercentage);\n\n if (protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) {\n LogPrint(\"masternode\",\"dsee - ignoring outdated Masternode %s protocol version %d < %d\\n\", vin.prevout.hash.ToString(), protocolVersion, masternodePayments.GetMinMasternodePaymentsProto());\n Misbehaving(pfrom->GetId(), 1);\n return;\n }\n\n CScript pubkeyScript;\n pubkeyScript = GetScriptForDestination(pubkey.GetID());\n\n if (pubkeyScript.size() != 25) {\n LogPrint(\"masternode\",\"dsee - pubkey the wrong size\\n\");\n Misbehaving(pfrom->GetId(), 100);\n return;\n }\n\n CScript pubkeyScript2;\n pubkeyScript2 = GetScriptForDestination(pubkey2.GetID());\n\n if (pubkeyScript2.size() != 25) {\n LogPrint(\"masternode\",\"dsee - pubkey2 the wrong size\\n\");\n Misbehaving(pfrom->GetId(), 100);\n return;\n }\n\n if (!vin.scriptSig.empty()) {\n LogPrint(\"masternode\",\"dsee - Ignore Not Empty ScriptSig %s\\n\", vin.prevout.hash.ToString());\n Misbehaving(pfrom->GetId(), 100);\n return;\n }\n\n std::string errorMessage = \"\";\n if (!obfuScationSigner.VerifyMessage(pubkey, vchSig, strMessage, errorMessage)) {\n LogPrint(\"masternode\",\"dsee - Got bad Masternode address signature\\n\");\n Misbehaving(pfrom->GetId(), 100);\n return;\n }\n\n if (Params().NetworkID() == CBaseChainParams::MAIN) {\n if (addr.GetPort() != 43088) return;\n } else if (addr.GetPort() == 43088)\n return;\n\n \/\/search existing Masternode list, this is where we update existing Masternodes with new dsee broadcasts\n CMasternode* pmn = this->Find(vin);\n if (pmn != NULL) {\n \/\/ count == -1 when it's a new entry\n \/\/ e.g. We don't want the entry relayed\/time updated when we're syncing the list\n \/\/ mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below,\n \/\/ after that they just need to match\n if (count == -1 && pmn->pubKeyCollateralAddress == pubkey && (GetAdjustedTime() - pmn->nLastDsee > MASTERNODE_MIN_MNB_SECONDS)) {\n if (pmn->protocolVersion > GETHEADERS_VERSION && sigTime - pmn->lastPing.sigTime < MASTERNODE_MIN_MNB_SECONDS) return;\n if (pmn->nLastDsee < sigTime) { \/\/take the newest entry\n LogPrint(\"masternode\", \"dsee - Got updated entry for %s\\n\", vin.prevout.hash.ToString());\n if (pmn->protocolVersion < GETHEADERS_VERSION) {\n pmn->pubKeyMasternode = pubkey2;\n pmn->sigTime = sigTime;\n pmn->sig = vchSig;\n pmn->protocolVersion = protocolVersion;\n pmn->addr = addr;\n \/\/fake ping\n pmn->lastPing = CMasternodePing(vin);\n }\n pmn->nLastDsee = sigTime;\n pmn->Check();\n if (pmn->IsEnabled()) {\n TRY_LOCK(cs_vNodes, lockNodes);\n if (!lockNodes) return;\n BOOST_FOREACH (CNode* pnode, vNodes)\n if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto())\n pnode->PushMessage(\"dsee\", vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage);\n }\n }\n }\n\n return;\n }\n\n static std::map mapSeenDsee;\n if (mapSeenDsee.count(vin.prevout) && mapSeenDsee[vin.prevout] == pubkey) {\n LogPrint(\"masternode\", \"dsee - already seen this vin %s\\n\", vin.prevout.ToString());\n return;\n }\n mapSeenDsee.insert(make_pair(vin.prevout, pubkey));\n \/\/ make sure the vout that was signed is related to the transaction that spawned the Masternode\n \/\/ - this is expensive, so it's only done once per Masternode\n if (!obfuScationSigner.IsVinAssociatedWithPubkey(vin, pubkey)) {\n LogPrint(\"masternode\",\"dsee - Got mismatched pubkey and vin\\n\");\n Misbehaving(pfrom->GetId(), 100);\n return;\n }\n\n\n LogPrint(\"masternode\", \"dsee - Got NEW OLD Masternode entry %s\\n\", vin.prevout.hash.ToString());\n\n \/\/ make sure it's still unspent\n \/\/ - this is checked later by .check() in many places and by ThreadCheckObfuScationPool()\n\n CValidationState state;\n CMutableTransaction tx = CMutableTransaction();\n CTxOut vout = CTxOut((GetMstrNodCollateral(chainActive.Height())-0.01) * COIN, obfuScationPool.collateralPubKey);\n tx.vin.push_back(vin);\n tx.vout.push_back(vout);\n\n bool fAcceptable = false;\n {\n TRY_LOCK(cs_main, lockMain);\n if (!lockMain) return;\n fAcceptable = AcceptableInputs(mempool, state, CTransaction(tx), false, NULL);\n }\n\n if (fAcceptable) {\n if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) {\n LogPrint(\"masternode\",\"dsee - Input must have least %d confirmations\\n\", MASTERNODE_MIN_CONFIRMATIONS);\n Misbehaving(pfrom->GetId(), 20);\n return;\n }\n\n \/\/ verify that sig time is legit in past\n \/\/ should be at least not earlier than block when 10000 MuBdI tx got MASTERNODE_MIN_CONFIRMATIONS\n uint256 hashBlock = 0;\n CTransaction tx2;\n GetTransaction(vin.prevout.hash, tx2, hashBlock, true);\n BlockMap::iterator mi = mapBlockIndex.find(hashBlock);\n if (mi != mapBlockIndex.end() && (*mi).second) {\n CBlockIndex* pMNIndex = (*mi).second; \/\/ block for 10000 MuBdI tx -> 1 confirmation\n CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; \/\/ block where tx got MASTERNODE_MIN_CONFIRMATIONS\n if (pConfIndex->GetBlockTime() > sigTime) {\n LogPrint(\"masternode\",\"mnb - Bad sigTime %d for Masternode %s (%i conf block is at %d)\\n\",\n sigTime, vin.prevout.hash.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime());\n return;\n }\n }\n\n \/\/ use this as a peer\n addrman.Add(CAddress(addr), pfrom->addr, 2 * 60 * 60);\n\n \/\/ add Masternode\n CMasternode mn = CMasternode();\n mn.addr = addr;\n mn.vin = vin;\n mn.pubKeyCollateralAddress = pubkey;\n mn.sig = vchSig;\n mn.sigTime = sigTime;\n mn.pubKeyMasternode = pubkey2;\n mn.protocolVersion = protocolVersion;\n \/\/ fake ping\n mn.lastPing = CMasternodePing(vin);\n mn.Check(true);\n \/\/ add v11 masternodes, v12 should be added by mnb only\n if (protocolVersion < GETHEADERS_VERSION) {\n LogPrint(\"masternode\", \"dsee - Accepted OLD Masternode entry %i %i\\n\", count, current);\n Add(mn);\n }\n if (mn.IsEnabled()) {\n TRY_LOCK(cs_vNodes, lockNodes);\n if (!lockNodes) return;\n BOOST_FOREACH (CNode* pnode, vNodes)\n if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto())\n pnode->PushMessage(\"dsee\", vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage);\n }\n } else {\n LogPrint(\"masternode\",\"dsee - Rejected Masternode entry %s\\n\", vin.prevout.hash.ToString());\n\n int nDoS = 0;\n if (state.IsInvalid(nDoS)) {\n LogPrint(\"masternode\",\"dsee - %s from %i %s was not accepted into the memory pool\\n\", tx.GetHash().ToString().c_str(),\n pfrom->GetId(), pfrom->cleanSubVer.c_str());\n if (nDoS > 0)\n Misbehaving(pfrom->GetId(), nDoS);\n }\n }\n }\n\n else if (strCommand == \"dseep\") { \/\/ObfuScation Election Entry Ping\n\n if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return;\n\n CTxIn vin;\n vector vchSig;\n int64_t sigTime;\n bool stop;\n vRecv >> vin >> vchSig >> sigTime >> stop;\n\n \/\/LogPrint(\"masternode\",\"dseep - Received: vin: %s sigTime: %lld stop: %s\\n\", vin.ToString().c_str(), sigTime, stop ? \"true\" : \"false\");\n\n if (sigTime > GetAdjustedTime() + 60 * 60) {\n LogPrint(\"masternode\",\"dseep - Signature rejected, too far into the future %s\\n\", vin.prevout.hash.ToString());\n Misbehaving(pfrom->GetId(), 1);\n return;\n }\n\n if (sigTime <= GetAdjustedTime() - 60 * 60) {\n LogPrint(\"masternode\",\"dseep - Signature rejected, too far into the past %s - %d %d \\n\", vin.prevout.hash.ToString(), sigTime, GetAdjustedTime());\n Misbehaving(pfrom->GetId(), 1);\n return;\n }\n\n std::map::iterator i = mWeAskedForMasternodeListEntry.find(vin.prevout);\n if (i != mWeAskedForMasternodeListEntry.end()) {\n int64_t t = (*i).second;\n if (GetTime() < t) return; \/\/ we've asked recently\n }\n\n \/\/ see if we have this Masternode\n CMasternode* pmn = this->Find(vin);\n if (pmn != NULL && pmn->protocolVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {\n \/\/ LogPrint(\"masternode\",\"dseep - Found corresponding mn for vin: %s\\n\", vin.ToString().c_str());\n \/\/ take this only if it's newer\n if (sigTime - pmn->nLastDseep > MASTERNODE_MIN_MNP_SECONDS) {\n std::string strMessage = pmn->addr.ToString() + boost::lexical_cast(sigTime) + boost::lexical_cast(stop);\n\n std::string errorMessage = \"\";\n if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {\n LogPrint(\"masternode\",\"dseep - Got bad Masternode address signature %s \\n\", vin.prevout.hash.ToString());\n \/\/Misbehaving(pfrom->GetId(), 100);\n return;\n }\n\n \/\/ fake ping for v11 masternodes, ignore for v12\n if (pmn->protocolVersion < GETHEADERS_VERSION) pmn->lastPing = CMasternodePing(vin);\n pmn->nLastDseep = sigTime;\n pmn->Check();\n if (pmn->IsEnabled()) {\n TRY_LOCK(cs_vNodes, lockNodes);\n if (!lockNodes) return;\n LogPrint(\"masternode\", \"dseep - relaying %s \\n\", vin.prevout.hash.ToString());\n BOOST_FOREACH (CNode* pnode, vNodes)\n if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto())\n pnode->PushMessage(\"dseep\", vin, vchSig, sigTime, stop);\n }\n }\n return;\n }\n\n LogPrint(\"masternode\", \"dseep - Couldn't find Masternode entry %s peer=%i\\n\", vin.prevout.hash.ToString(), pfrom->GetId());\n\n AskForMN(pfrom, vin);\n }\n\n \/*\n * END OF \"REMOVE\"\n *\/\n}\n\nvoid CMasternodeMan::Remove(CTxIn vin)\n{\n LOCK(cs);\n\n vector::iterator it = vMasternodes.begin();\n while (it != vMasternodes.end()) {\n if ((*it).vin == vin) {\n LogPrint(\"masternode\", \"CMasternodeMan: Removing Masternode %s - %i now\\n\", (*it).vin.prevout.hash.ToString(), size() - 1);\n vMasternodes.erase(it);\n break;\n }\n ++it;\n }\n}\n\nvoid CMasternodeMan::UpdateMasternodeList(CMasternodeBroadcast mnb)\n{\n LOCK(cs);\n mapSeenMasternodePing.insert(std::make_pair(mnb.lastPing.GetHash(), mnb.lastPing));\n mapSeenMasternodeBroadcast.insert(std::make_pair(mnb.GetHash(), mnb));\n\n LogPrint(\"masternode\",\"CMasternodeMan::UpdateMasternodeList -- masternode=%s\\n\", mnb.vin.prevout.ToStringShort());\n\n CMasternode* pmn = Find(mnb.vin);\n if (pmn == NULL) {\n CMasternode mn(mnb);\n if (Add(mn)) {\n masternodeSync.AddedMasternodeList(mnb.GetHash());\n }\n } else if (pmn->UpdateFromNewBroadcast(mnb)) {\n masternodeSync.AddedMasternodeList(mnb.GetHash());\n }\n}\n\nstd::string CMasternodeMan::ToString() const\n{\n std::ostringstream info;\n\n info << \"Masternodes: \" << (int)vMasternodes.size() << \", peers who asked us for Masternode list: \" << (int)mAskedUsForMasternodeList.size() << \", peers we asked for Masternode list: \" << (int)mWeAskedForMasternodeList.size() << \", entries in Masternode list we asked for: \" << (int)mWeAskedForMasternodeListEntry.size() << \", nDsqCount: \" << (int)nDsqCount;\n\n return info.str();\n}\n","avg_line_length":37.0882103478,"max_line_length":362,"alphanum_fraction":0.6004528095} {"size":1399,"ext":"cpp","lang":"C++","max_stars_count":2.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ Copyright (c) 2015 Microsoft Corporation. All rights reserved.\r\n\/\/\r\n\/\/ This code is licensed under the MIT License (MIT).\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n#include \/\/ for std::exit\r\n#include \/\/ for span\r\n\r\nint operator_subscript_no_throw() noexcept\r\n{\r\n int arr[10]; \r\n const gsl::span sp { arr };\r\n return sp[11];\r\n}\r\n\r\n\r\nvoid test_terminate()\r\n{ \r\n std::exit(0);\r\n}\r\n\r\nvoid setup_termination_handler() noexcept\r\n{\r\n#if defined(_MSC_VER)\r\n\r\n auto& handler = gsl::details::get_terminate_handler();\r\n handler = &test_terminate;\r\n\r\n#else\r\n\r\n std::set_terminate(test_terminate);\r\n\r\n#endif\r\n}\r\n\r\n\r\nint main() noexcept\r\n{\r\n setup_termination_handler();\r\n operator_subscript_no_throw();\r\n return -1;\r\n}\r\n","avg_line_length":25.9074074074,"max_line_length":81,"alphanum_fraction":0.5997140815} {"size":98259,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/*\n * By downloading, copying, installing or using the software you agree to this license.\n * If you do not agree to this license, do not download, install,\n * copy or use the software.\n *\n *\n * License Agreement\n * For Open Source Computer Vision Library\n * (3-clause BSD License)\n *\n * Copyright (C) 2015, NVIDIA Corporation, all rights reserved.\n * Third party copyrights are property of their respective owners.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * * Neither the names of the copyright holders nor the names of the contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * This software is provided by the copyright holders and contributors \"as is\" and\n * any express or implied warranties, including, but not limited to, the implied\n * warranties of merchantability and fitness for a particular purpose are disclaimed.\n * In no event shall copyright holders or contributors be liable for any direct,\n * indirect, incidental, special, exemplary, or consequential damages\n * (including, but not limited to, procurement of substitute goods or services;\n * loss of use, data, or profits; or business interruption) however caused\n * and on any theory of liability, whether in contract, strict liability,\n * or tort (including negligence or otherwise) arising in any way out of\n * the use of this software, even if advised of the possibility of such damage.\n *\/\n\n#include \"common.hpp\"\n#include \"vtransform.hpp\"\n\n#include \n#include \n#include \n\nnamespace CAROTENE_NS {\n\nbool isResizeNearestNeighborSupported(const Size2D &ssize, u32 elemSize)\n{\n#if SIZE_MAX <= UINT32_MAX\n (void)ssize;\n#endif\n bool supportedElemSize = (elemSize == 1) || (elemSize == 3) || (elemSize == 4);\n return isSupportedConfiguration()\n#if SIZE_MAX > UINT32_MAX\n && !(ssize.width > 0xffffFFFF || ssize.height > 0xffffFFFF)\/\/ Restrict image size since internally used resizeGeneric performs\n \/\/ index evaluation with u32\n#endif\n && supportedElemSize;\n}\n\nbool isResizeAreaSupported(f32 wr, f32 hr, u32 channels)\n{\n bool supportedRatio = false;\n\n if (channels == 1)\n supportedRatio = (hr == wr) && ((wr == 2.0f) || (wr == 4.0f) || (wr == 0.5));\n else if (channels == 3)\n supportedRatio = (hr == wr) && ((wr == 2.0f) || (wr == 4.0f) || (wr == 0.5f));\n else if (channels == 4)\n supportedRatio = (hr == wr) && ((wr == 2.0f) || (wr == 4.0f) || (wr == 0.5f));\n\n return isSupportedConfiguration() && supportedRatio;\n}\n\nbool isResizeLinearSupported(const Size2D &ssize, const Size2D &dsize,\n f32 wr, f32 hr, u32 channels)\n{\n if ((wr <= 2.0f) && (hr <= 2.0f))\n {\n bool channelsSupport = (channels == 1) || (channels == 3) || (channels == 4);\n return (ssize.width >= 16) && (dsize.height >= 8) &&\n (dsize.width >= 8) && channelsSupport;\n }\n\n return false;\n}\n\nbool isResizeLinearOpenCVSupported(const Size2D &ssize, const Size2D &dsize, u32 channels)\n{\n switch(channels)\n {\n case 1:\n if (ssize.width >= 8\n#if SIZE_MAX > UINT32_MAX\n && !(ssize.width > 0xffffFFFF || ssize.height > 0xffffFFFF)\/\/ Restrict image size since internal index evaluation\n \/\/ is performed with u32\n#endif\n && dsize.width >= 8 && dsize.height >= 8)\n return isSupportedConfiguration();\n return false;\n case 4:\n if (ssize.width >= 2\n#if SIZE_MAX > UINT32_MAX\n && !(ssize.width > 0xffffFFFF || ssize.height > 0xffffFFFF)\/\/ Restrict image size since internal index evaluation\n \/\/ is performed with u32\n#endif\n && dsize.width >= 2 && dsize.height >= 8)\n return isSupportedConfiguration();\n default:\n return false;\n };\n}\n\n#ifdef CAROTENE_NEON\n\nnamespace {\n\nu32 * calcLUT(size_t size, f32 ratio,\n std::vector & _ofs)\n{\n _ofs.resize(size);\n u32 * ofs = &_ofs[0];\n\n size_t roiw8 = size >= 7 ? size - 7 : 0;\n size_t roiw4 = size >= 3 ? size - 3 : 0;\n size_t x = 0;\n\n f32 indeces[4] = { 0, 1, 2, 3 };\n float32x4_t v_index = vld1q_f32(indeces), v_inc = vdupq_n_f32(4);\n float32x4_t v_05 = vdupq_n_f32(0.5f), v_ratio = vdupq_n_f32(ratio);\n\n for ( ; x < roiw8; x += 8)\n {\n float32x4_t v_dstf = vmulq_f32(vaddq_f32(v_index, v_05), v_ratio);\n vst1q_u32(ofs + x, vcvtq_u32_f32(v_dstf));\n v_index = vaddq_f32(v_index, v_inc);\n\n v_dstf = vmulq_f32(vaddq_f32(v_index, v_05), v_ratio);\n vst1q_u32(ofs + x + 4, vcvtq_u32_f32(v_dstf));\n v_index = vaddq_f32(v_index, v_inc);\n }\n\n for ( ; x < roiw4; x += 4)\n {\n float32x4_t v_dstf = vmulq_f32(vaddq_f32(v_index, v_05), v_ratio);\n vst1q_u32(ofs + x, vcvtq_u32_f32(v_dstf));\n v_index = vaddq_f32(v_index, v_inc);\n }\n\n for ( ; x < size; ++x)\n {\n ofs[x] = static_cast(floorf((x + 0.5f) * ratio));\n }\n\n return ofs;\n}\n\ntemplate \nvoid resizeGeneric(const Size2D &dsize,\n const void * srcBase, ptrdiff_t srcStride,\n void * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr)\n{\n std::vector _x_ofs;\n u32 * x_ofs = calcLUT(dsize.width, wr, _x_ofs);\/\/32bit LUT is used so we could get issues on src image dimensions greater than (2^32-1)\n\n for (size_t dst_y = 0; dst_y < dsize.height; ++dst_y)\n {\n size_t src_y = static_cast(floorf((dst_y + 0.5f) * hr));\n const T * src = internal::getRowPtr(static_cast(srcBase), srcStride, src_y);\n T * dst = internal::getRowPtr(static_cast(dstBase), dstStride, dst_y);\n\n for (size_t dst_x = 0; dst_x < dsize.width; ++dst_x)\n {\n internal::prefetch(src + dst_x);\n dst[dst_x] = src[x_ofs[dst_x]];\n }\n }\n}\n\ntypedef struct _24bit_\n{\n u8 a[3];\n} _24bit;\n\n} \/\/ namespace\n\n\n#endif\n\nvoid resizeNearestNeighbor(const Size2D &ssize, const Size2D &dsize,\n const void * srcBase, ptrdiff_t srcStride,\n void * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr, u32 elemSize)\n{\n internal::assertSupportedConfiguration(wr > 0 && hr > 0 &&\n (dsize.width - 0.5) * wr < ssize.width &&\n (dsize.height - 0.5) * hr < ssize.height && \/\/ Ensure we have enough source data\n (dsize.width + 0.5) * wr >= ssize.width &&\n (dsize.height + 0.5) * hr >= ssize.height && \/\/ Ensure source isn't too big\n isResizeNearestNeighborSupported(ssize, elemSize));\n#ifdef CAROTENE_NEON\n\n if (elemSize == 1)\n {\n resizeGeneric(dsize,\n srcBase, srcStride,\n dstBase, dstStride,\n wr, hr);\n }\n else if (elemSize == 3)\n {\n resizeGeneric<_24bit>(dsize,\n srcBase, srcStride,\n dstBase, dstStride,\n wr, hr);\n }\n else if (elemSize == 4)\n {\n resizeGeneric(dsize,\n srcBase, srcStride,\n dstBase, dstStride,\n wr, hr);\n }\n\n#else\n (void)dsize;\n (void)srcBase;\n (void)srcStride;\n (void)dstBase;\n (void)dstStride;\n (void)wr;\n (void)hr;\n#endif\n}\n\n#ifdef CAROTENE_NEON\ntemplate \ninline uint8x8_t areaDownsamplingDivision(uint16x8_t data)\n{\n return vshrn_n_u16(data, shiftsize);\n}\ntemplate <>\ninline uint8x8_t areaDownsamplingDivision(uint16x8_t data)\n{\n \/\/ rounding\n return vrshrn_n_u16(data,2);\n}\ntemplate <>\ninline uint8x8_t areaDownsamplingDivision(uint16x8_t data)\n{\n \/\/ bankers rounding\n return vrshrn_n_u16(vqsubq_u16(data, vshrq_n_u16(vbicq_u16(vdupq_n_u16(1<<4), data), 4)),4);\n}\n\ntemplate \ninline u8 areaDownsamplingDivision(u16 data)\n{\n return data >> shiftsize;\n}\ntemplate <>\ninline u8 areaDownsamplingDivision(u16 data)\n{\n \/\/ rounding\n return (data + 2) >> 2;\n}\ntemplate <>\ninline u8 areaDownsamplingDivision(u16 data)\n{\n \/\/ bankers rounding\n return (data - (((1<<4) & ~data) >> 4) + 8) >> 4;\n}\n#endif\n\ntemplate \ninline void resizeAreaRounding(const Size2D &ssize, const Size2D &dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr, u32 channels)\n{\n internal::assertSupportedConfiguration(isResizeAreaSupported(wr, hr, channels) &&\n std::abs(dsize.width * wr - ssize.width) < 0.1 &&\n std::abs(dsize.height * hr - ssize.height) < 0.1);\n#ifdef CAROTENE_NEON\n if (channels == 1)\n {\n if ((wr == 2.0f) && (hr == 2.0f))\n {\n size_t roiw8 = dsize.width >= 7 ? dsize.width - 7 : 0;\n\n for (size_t i = 0; i < dsize.height; ++i)\n {\n const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 1);\n const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 1) + 1);\n u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n size_t sj = 0, dj = 0;\n\n for ( ; dj < roiw8; dj += 8, sj += 16)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n\n uint16x8_t vSum1 = vpaddlq_u8(vld1q_u8(src0_row + sj));\n uint16x8_t vSum2 = vpaddlq_u8(vld1q_u8(src1_row + sj));\n uint8x8_t vRes1 = areaDownsamplingDivision(vaddq_u16(vSum1, vSum2));\n\n vst1_u8(dst_row + dj, vRes1);\n }\n\n for ( ; dj < dsize.width; ++dj, sj += 2)\n {\n dst_row[dj] = areaDownsamplingDivision(\n (u16)src0_row[sj] + src0_row[sj + 1] +\n src1_row[sj] + src1_row[sj + 1]);\n }\n }\n }\n else if ((wr == 0.5f) && (hr == 0.5f))\n {\n size_t roiw32 = dsize.width >= 31 ? dsize.width - 31 : 0;\n size_t roiw16 = dsize.width >= 15 ? dsize.width - 15 : 0;\n\n for (size_t i = 0; i < dsize.height; i += 2)\n {\n const u8 * src_row = internal::getRowPtr(srcBase, srcStride, i >> 1);\n u8 * dst0_row = internal::getRowPtr(dstBase, dstStride, i);\n u8 * dst1_row = internal::getRowPtr(dstBase, dstStride, std::min(i + 1, dsize.height - 1));\n size_t sj = 0, dj = 0;\n\n for ( ; dj < roiw32; dj += 32, sj += 16)\n {\n internal::prefetch(src_row + sj);\n\n uint8x16x2_t v_dst;\n v_dst.val[0] = v_dst.val[1] = vld1q_u8(src_row + sj);\n\n vst2q_u8(dst0_row + dj, v_dst);\n vst2q_u8(dst1_row + dj, v_dst);\n }\n\n for ( ; dj < roiw16; dj += 16, sj += 8)\n {\n uint8x8x2_t v_dst;\n v_dst.val[0] = v_dst.val[1] = vld1_u8(src_row + sj);\n\n vst2_u8(dst0_row + dj, v_dst);\n vst2_u8(dst1_row + dj, v_dst);\n }\n\n for ( ; dj < dsize.width; dj += 2, ++sj)\n {\n u8 src_val = src_row[sj];\n dst0_row[dj] = dst0_row[dj + 1] = src_val;\n dst1_row[dj] = dst1_row[dj + 1] = src_val;\n }\n }\n }\n else \/\/if ((wr == 4.0f) && (hr == 4.0f)) \/\/the only scale that lasts after isSupported check\n {\n#ifndef ANDROID\n size_t roiw16 = dsize.width >= 15 ? dsize.width - 15 : 0;\n#endif\n size_t roiw8 = dsize.width >= 7 ? dsize.width - 7 : 0;\n\n for (size_t i = 0; i < dsize.height; ++i)\n {\n const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 2);\n const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 1);\n const u8 * src2_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 2);\n const u8 * src3_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 3);\n u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n for ( ; dj < roiw16; dj += 16, sj += 64)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n internal::prefetch(src2_row + sj);\n internal::prefetch(src3_row + sj);\n\n uint8x16x4_t vLane1 = vld4q_u8(src0_row + sj);\n uint8x16x4_t vLane2 = vld4q_u8(src1_row + sj);\n uint8x16x4_t vLane3 = vld4q_u8(src2_row + sj);\n uint8x16x4_t vLane4 = vld4q_u8(src3_row + sj);\n\n uint16x8_t vSum_0 = vaddl_u8(vget_low_u8(vLane1.val[0]), vget_low_u8(vLane1.val[1]));\n vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane1.val[2]), vget_low_u8(vLane1.val[3])));\n vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane2.val[0]), vget_low_u8(vLane2.val[1])));\n vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane2.val[2]), vget_low_u8(vLane2.val[3])));\n vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane3.val[0]), vget_low_u8(vLane3.val[1])));\n vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane3.val[2]), vget_low_u8(vLane3.val[3])));\n vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane4.val[0]), vget_low_u8(vLane4.val[1])));\n vSum_0 = vaddq_u16(vSum_0, vaddl_u8(vget_low_u8(vLane4.val[2]), vget_low_u8(vLane4.val[3])));\n\n uint16x8_t vSum_1 = vaddl_u8(vget_high_u8(vLane1.val[0]), vget_high_u8(vLane1.val[1]));\n vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane1.val[2]), vget_high_u8(vLane1.val[3])));\n vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane2.val[0]), vget_high_u8(vLane2.val[1])));\n vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane2.val[2]), vget_high_u8(vLane2.val[3])));\n vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane3.val[0]), vget_high_u8(vLane3.val[1])));\n vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane3.val[2]), vget_high_u8(vLane3.val[3])));\n vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane4.val[0]), vget_high_u8(vLane4.val[1])));\n vSum_1 = vaddq_u16(vSum_1, vaddl_u8(vget_high_u8(vLane4.val[2]), vget_high_u8(vLane4.val[3])));\n\n uint8x8_t vRes_0 = areaDownsamplingDivision(vSum_0);\n uint8x8_t vRes_1 = areaDownsamplingDivision(vSum_1);\n\n vst1q_u8(dst_row + dj, vcombine_u8(vRes_0, vRes_1));\n }\n#endif\n\n for ( ; dj < roiw8; dj += 8, sj += 32)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n internal::prefetch(src2_row + sj);\n internal::prefetch(src3_row + sj);\n\n uint8x8x4_t vLane1 = vld4_u8(src0_row + sj);\n uint8x8x4_t vLane2 = vld4_u8(src1_row + sj);\n uint8x8x4_t vLane3 = vld4_u8(src2_row + sj);\n uint8x8x4_t vLane4 = vld4_u8(src3_row + sj);\n\n uint16x8_t vSum = vaddl_u8(vLane1.val[0], vLane1.val[1]);\n vSum = vaddq_u16(vSum, vaddl_u8(vLane1.val[2], vLane1.val[3]));\n vSum = vaddq_u16(vSum, vaddl_u8(vLane2.val[0], vLane2.val[1]));\n vSum = vaddq_u16(vSum, vaddl_u8(vLane2.val[2], vLane2.val[3]));\n vSum = vaddq_u16(vSum, vaddl_u8(vLane3.val[0], vLane3.val[1]));\n vSum = vaddq_u16(vSum, vaddl_u8(vLane3.val[2], vLane3.val[3]));\n vSum = vaddq_u16(vSum, vaddl_u8(vLane4.val[0], vLane4.val[1]));\n vSum = vaddq_u16(vSum, vaddl_u8(vLane4.val[2], vLane4.val[3]));\n\n vst1_u8(dst_row + dj, areaDownsamplingDivision(vSum));\n }\n\n for ( ; dj < dsize.width; ++dj, sj += 4)\n {\n dst_row[dj] = areaDownsamplingDivision(\n (u16)src0_row[sj] + src0_row[sj + 1] + src0_row[sj + 2] + src0_row[sj + 3] +\n src1_row[sj] + src1_row[sj + 1] + src1_row[sj + 2] + src1_row[sj + 3] +\n src2_row[sj] + src2_row[sj + 1] + src2_row[sj + 2] + src2_row[sj + 3] +\n src3_row[sj] + src3_row[sj + 1] + src3_row[sj + 2] + src3_row[sj + 3]);\n }\n }\n }\n }\n else if (channels == 4)\n {\n if ((wr == 2.0f) && (hr == 2.0f))\n {\n#ifndef ANDROID\n size_t roiw4 = dsize.width >= 3 ? (dsize.width - 3) << 2 : 0;\n#endif\n size_t roiw2 = dsize.width >= 1 ? (dsize.width - 1) << 2 : 0;\n\n for (size_t i = 0; i < dsize.height; ++i)\n {\n const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 1);\n const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 1) + 1);\n u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n for ( ; dj < roiw4; dj += 16, sj += 32)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n\n uint8x8_t vRes_0, vRes_1;\n\n {\n uint8x16_t vLane1 = vld1q_u8(src0_row + sj);\n uint8x16_t vLane2 = vld1q_u8(src1_row + sj);\n\n uint16x8_t vLane_l = vaddl_u8(vget_low_u8(vLane1), vget_low_u8(vLane2));\n uint16x8_t vLane_h = vaddl_u8(vget_high_u8(vLane1), vget_high_u8(vLane2));\n\n uint16x4_t vSum_l = vadd_u16(vget_low_u16(vLane_l), vget_high_u16(vLane_l));\n uint16x4_t vSum_h = vadd_u16(vget_low_u16(vLane_h), vget_high_u16(vLane_h));\n\n vRes_0 = areaDownsamplingDivision(vcombine_u16(vSum_l, vSum_h));\n }\n\n {\n uint8x16_t vLane1 = vld1q_u8(src0_row + sj + 16);\n uint8x16_t vLane2 = vld1q_u8(src1_row + sj + 16);\n\n uint16x8_t vLane_l = vaddl_u8(vget_low_u8(vLane1), vget_low_u8(vLane2));\n uint16x8_t vLane_h = vaddl_u8(vget_high_u8(vLane1), vget_high_u8(vLane2));\n\n uint16x4_t vSum_l = vadd_u16(vget_low_u16(vLane_l), vget_high_u16(vLane_l));\n uint16x4_t vSum_h = vadd_u16(vget_low_u16(vLane_h), vget_high_u16(vLane_h));\n\n vRes_1 = areaDownsamplingDivision(vcombine_u16(vSum_l, vSum_h));\n }\n\n vst1q_u8(dst_row + dj, vcombine_u8(vRes_0, vRes_1));\n }\n#endif\n\n for ( ; dj < roiw2; dj += 8, sj += 16)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n\n uint8x16_t vLane1 = vld1q_u8(src0_row + sj);\n uint8x16_t vLane2 = vld1q_u8(src1_row + sj);\n\n uint16x8_t vLane_l = vaddl_u8(vget_low_u8(vLane1), vget_low_u8(vLane2));\n uint16x8_t vLane_h = vaddl_u8(vget_high_u8(vLane1), vget_high_u8(vLane2));\n\n uint16x4_t vSum_l = vadd_u16(vget_low_u16(vLane_l), vget_high_u16(vLane_l));\n uint16x4_t vSum_h = vadd_u16(vget_low_u16(vLane_h), vget_high_u16(vLane_h));\n\n uint8x8_t vRes = areaDownsamplingDivision(vcombine_u16(vSum_l, vSum_h));\n vst1_u8(dst_row + dj, vRes);\n }\n\n for (size_t dwidth = dsize.width << 2; dj < dwidth; dj += 4, sj += 8)\n {\n dst_row[dj ] = areaDownsamplingDivision(\n (u16)src0_row[sj ] + src0_row[sj + 4] +\n src1_row[sj ] + src1_row[sj + 4]);\n dst_row[dj + 1] = areaDownsamplingDivision(\n (u16)src0_row[sj + 1] + src0_row[sj + 5] +\n src1_row[sj + 1] + src1_row[sj + 5]);\n dst_row[dj + 2] = areaDownsamplingDivision(\n (u16)src0_row[sj + 2] + src0_row[sj + 6] +\n src1_row[sj + 2] + src1_row[sj + 6]);\n dst_row[dj + 3] = areaDownsamplingDivision(\n (u16)src0_row[sj + 3] + src0_row[sj + 7] +\n src1_row[sj + 3] + src1_row[sj + 7]);\n }\n }\n }\n else if ((wr == 0.5f) && (hr == 0.5f))\n {\n#ifndef ANDROID\n size_t roiw32 = dsize.width >= 31 ? (dsize.width - 31) << 2 : 0;\n#endif\n size_t roiw16 = dsize.width >= 15 ? (dsize.width - 15) << 2 : 0;\n\n for (size_t i = 0; i < dsize.height; i += 2)\n {\n const u8 * src_row = internal::getRowPtr(srcBase, srcStride, i >> 1);\n u8 * dst0_row = internal::getRowPtr(dstBase, dstStride, i);\n u8 * dst1_row = internal::getRowPtr(dstBase, dstStride, std::min(i + 1, dsize.height - 1));\n size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n for ( ; dj < roiw32; dj += 128, sj += 64)\n {\n internal::prefetch(src_row + sj);\n\n uint8x16x4_t v_src = vld4q_u8(src_row + sj);\n uint8x16x2_t v_c0 = vzipq_u8(v_src.val[0], v_src.val[0]);\n uint8x16x2_t v_c1 = vzipq_u8(v_src.val[1], v_src.val[1]);\n uint8x16x2_t v_c2 = vzipq_u8(v_src.val[2], v_src.val[2]);\n uint8x16x2_t v_c3 = vzipq_u8(v_src.val[3], v_src.val[3]);\n\n uint8x16x4_t v_dst;\n v_dst.val[0] = v_c0.val[0];\n v_dst.val[1] = v_c1.val[0];\n v_dst.val[2] = v_c2.val[0];\n v_dst.val[3] = v_c3.val[0];\n vst4q_u8(dst0_row + dj, v_dst);\n vst4q_u8(dst1_row + dj, v_dst);\n\n v_dst.val[0] = v_c0.val[1];\n v_dst.val[1] = v_c1.val[1];\n v_dst.val[2] = v_c2.val[1];\n v_dst.val[3] = v_c3.val[1];\n vst4q_u8(dst0_row + dj + 64, v_dst);\n vst4q_u8(dst1_row + dj + 64, v_dst);\n }\n#endif\n\n for ( ; dj < roiw16; dj += 64, sj += 32)\n {\n internal::prefetch(src_row + sj);\n\n uint8x8x4_t v_src = vld4_u8(src_row + sj);\n uint8x8x2_t v_c0 = vzip_u8(v_src.val[0], v_src.val[0]);\n uint8x8x2_t v_c1 = vzip_u8(v_src.val[1], v_src.val[1]);\n uint8x8x2_t v_c2 = vzip_u8(v_src.val[2], v_src.val[2]);\n uint8x8x2_t v_c3 = vzip_u8(v_src.val[3], v_src.val[3]);\n\n uint8x16x4_t v_dst;\n v_dst.val[0] = vcombine_u8(v_c0.val[0], v_c0.val[1]);\n v_dst.val[1] = vcombine_u8(v_c1.val[0], v_c1.val[1]);\n v_dst.val[2] = vcombine_u8(v_c2.val[0], v_c2.val[1]);\n v_dst.val[3] = vcombine_u8(v_c3.val[0], v_c3.val[1]);\n vst4q_u8(dst0_row + dj, v_dst);\n vst4q_u8(dst1_row + dj, v_dst);\n }\n\n for (size_t dwidth = dsize.width << 2; dj < dwidth; dj += 8, sj += 4)\n {\n u8 src_val = src_row[sj];\n dst0_row[dj] = dst0_row[dj + 4] = src_val;\n dst1_row[dj] = dst1_row[dj + 4] = src_val;\n\n src_val = src_row[sj + 1];\n dst0_row[dj + 1] = dst0_row[dj + 5] = src_val;\n dst1_row[dj + 1] = dst1_row[dj + 5] = src_val;\n\n src_val = src_row[sj + 2];\n dst0_row[dj + 2] = dst0_row[dj + 6] = src_val;\n dst1_row[dj + 2] = dst1_row[dj + 6] = src_val;\n\n src_val = src_row[sj + 3];\n dst0_row[dj + 3] = dst0_row[dj + 7] = src_val;\n dst1_row[dj + 3] = dst1_row[dj + 7] = src_val;\n }\n }\n }\n else \/\/if ((hr == 4.0f) && (wr == 4.0f)) \/\/the only scale that lasts after isSupported check\n {\n size_t roiw4 = dsize.width >= 3 ? (dsize.width - 3) << 2 : 0;\n size_t roiw2 = dsize.width >= 1 ? (dsize.width - 1) << 2 : 0;\n\n for (size_t i = 0; i < dsize.height; ++i)\n {\n const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 2);\n const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 1);\n const u8 * src2_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 2);\n const u8 * src3_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 3);\n u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n size_t sj = 0, dj = 0;\n\n for ( ; dj < roiw4; dj += 16, sj += 64)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n internal::prefetch(src2_row + sj);\n internal::prefetch(src3_row + sj);\n\n uint8x16_t vLane10 = vld1q_u8(src0_row + sj), vLane11 = vld1q_u8(src0_row + sj + 16);\n uint8x16_t vLane20 = vld1q_u8(src1_row + sj), vLane21 = vld1q_u8(src1_row + sj + 16);\n uint8x16_t vLane30 = vld1q_u8(src2_row + sj), vLane31 = vld1q_u8(src2_row + sj + 16);\n uint8x16_t vLane40 = vld1q_u8(src3_row + sj), vLane41 = vld1q_u8(src3_row + sj + 16);\n\n uint16x8_t v_part_0, v_part_1;\n {\n uint16x8_t v_sum0 = vaddl_u8(vget_low_u8(vLane10), vget_high_u8(vLane10));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane20), vget_high_u8(vLane20)));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane30), vget_high_u8(vLane30)));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane40), vget_high_u8(vLane40)));\n\n uint16x8_t v_sum1 = vaddl_u8(vget_low_u8(vLane11), vget_high_u8(vLane11));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane21), vget_high_u8(vLane21)));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane31), vget_high_u8(vLane31)));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane41), vget_high_u8(vLane41)));\n\n v_part_0 = vcombine_u16(vadd_u16(vget_low_u16(v_sum0), vget_high_u16(v_sum0)),\n vadd_u16(vget_low_u16(v_sum1), vget_high_u16(v_sum1)));\n }\n\n vLane10 = vld1q_u8(src0_row + sj + 32);\n vLane11 = vld1q_u8(src0_row + sj + 48);\n vLane20 = vld1q_u8(src1_row + sj + 32);\n vLane21 = vld1q_u8(src1_row + sj + 48);\n vLane30 = vld1q_u8(src2_row + sj + 32);\n vLane31 = vld1q_u8(src2_row + sj + 48);\n vLane40 = vld1q_u8(src3_row + sj + 32);\n vLane41 = vld1q_u8(src3_row + sj + 48);\n\n {\n uint16x8_t v_sum0 = vaddl_u8(vget_low_u8(vLane10), vget_high_u8(vLane10));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane20), vget_high_u8(vLane20)));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane30), vget_high_u8(vLane30)));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane40), vget_high_u8(vLane40)));\n\n uint16x8_t v_sum1 = vaddl_u8(vget_low_u8(vLane11), vget_high_u8(vLane11));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane21), vget_high_u8(vLane21)));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane31), vget_high_u8(vLane31)));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane41), vget_high_u8(vLane41)));\n\n v_part_1 = vcombine_u16(vadd_u16(vget_low_u16(v_sum0), vget_high_u16(v_sum0)),\n vadd_u16(vget_low_u16(v_sum1), vget_high_u16(v_sum1)));\n }\n\n vst1q_u8(dst_row + dj, vcombine_u8(areaDownsamplingDivision(v_part_0),\n areaDownsamplingDivision(v_part_1)));\n }\n\n for ( ; dj < roiw2; dj += 8, sj += 32)\n {\n uint8x16_t vLane10 = vld1q_u8(src0_row + sj), vLane11 = vld1q_u8(src0_row + sj + 16);\n uint8x16_t vLane20 = vld1q_u8(src1_row + sj), vLane21 = vld1q_u8(src1_row + sj + 16);\n uint8x16_t vLane30 = vld1q_u8(src2_row + sj), vLane31 = vld1q_u8(src2_row + sj + 16);\n uint8x16_t vLane40 = vld1q_u8(src3_row + sj), vLane41 = vld1q_u8(src3_row + sj + 16);\n\n uint16x8_t v_sum0 = vaddl_u8(vget_low_u8(vLane10), vget_high_u8(vLane10));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane20), vget_high_u8(vLane20)));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane30), vget_high_u8(vLane30)));\n v_sum0 = vaddq_u16(v_sum0, vaddl_u8(vget_low_u8(vLane40), vget_high_u8(vLane40)));\n\n uint16x8_t v_sum1 = vaddl_u8(vget_low_u8(vLane11), vget_high_u8(vLane11));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane21), vget_high_u8(vLane21)));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane31), vget_high_u8(vLane31)));\n v_sum1 = vaddq_u16(v_sum1, vaddl_u8(vget_low_u8(vLane41), vget_high_u8(vLane41)));\n\n uint16x8_t v_sum = vcombine_u16(vadd_u16(vget_low_u16(v_sum0), vget_high_u16(v_sum0)),\n vadd_u16(vget_low_u16(v_sum1), vget_high_u16(v_sum1)));\n\n vst1_u8(dst_row + dj, areaDownsamplingDivision(v_sum));\n }\n\n for (size_t dwidth = dsize.width << 2; dj < dwidth; dj += 4, sj += 16)\n {\n dst_row[dj ] = areaDownsamplingDivision(\n (u16)src0_row[sj ] + src0_row[sj + 4] +\n src0_row[sj + 8] + src0_row[sj + 12] +\n src1_row[sj ] + src1_row[sj + 4] +\n src1_row[sj + 8] + src1_row[sj + 12] +\n src2_row[sj ] + src2_row[sj + 4] +\n src2_row[sj + 8] + src2_row[sj + 12] +\n src3_row[sj ] + src3_row[sj + 4] +\n src3_row[sj + 8] + src3_row[sj + 12]);\n\n dst_row[dj + 1] = areaDownsamplingDivision(\n (u16)src0_row[sj + 1] + src0_row[sj + 5] +\n src0_row[sj + 9] + src0_row[sj + 13] +\n src1_row[sj + 1] + src1_row[sj + 5] +\n src1_row[sj + 9] + src1_row[sj + 13] +\n src2_row[sj + 1] + src2_row[sj + 5] +\n src2_row[sj + 9] + src2_row[sj + 13] +\n src3_row[sj + 1] + src3_row[sj + 5] +\n src3_row[sj + 9] + src3_row[sj + 13]);\n\n dst_row[dj + 2] = areaDownsamplingDivision(\n (u16)src0_row[sj + 2] + src0_row[sj + 6] +\n src0_row[sj + 10] + src0_row[sj + 14] +\n src1_row[sj + 2] + src1_row[sj + 6] +\n src1_row[sj + 10] + src1_row[sj + 14] +\n src2_row[sj + 2] + src2_row[sj + 6] +\n src2_row[sj + 10] + src2_row[sj + 14] +\n src3_row[sj + 2] + src3_row[sj + 6] +\n src3_row[sj + 10] + src3_row[sj + 14]);\n\n dst_row[dj + 3] = areaDownsamplingDivision(\n (u16)src0_row[sj + 3] + src0_row[sj + 7] +\n src0_row[sj + 11] + src0_row[sj + 15] +\n src1_row[sj + 3] + src1_row[sj + 7] +\n src1_row[sj + 11] + src1_row[sj + 15] +\n src2_row[sj + 3] + src2_row[sj + 7] +\n src2_row[sj + 11] + src2_row[sj + 15] +\n src3_row[sj + 3] + src3_row[sj + 7] +\n src3_row[sj + 11] + src3_row[sj + 15]);\n }\n }\n }\n }\n else if (channels == 3)\n {\n if ((wr == 2.0f) && (wr == 2.0f))\n {\n#ifndef ANDROID\n size_t roiw16 = dsize.width >= 15 ? (dsize.width - 15) * 3 : 0;\n#endif\n size_t roiw8 = dsize.width >= 7 ? (dsize.width - 7) * 3 : 0;\n\n for (size_t i = 0; i < dsize.height; ++i)\n {\n const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 1);\n const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 1) + 1);\n u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n for ( ; dj < roiw16; dj += 48, sj += 96)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n\n uint8x16x3_t vLane1 = vld3q_u8(src0_row + sj);\n uint8x16x3_t vLane2 = vld3q_u8(src1_row + sj);\n\n uint8x8x3_t v_dst0, v_dst1;\n {\n uint16x8_t v_el0 = vpaddlq_u8(vLane1.val[0]);\n uint16x8_t v_el1 = vpaddlq_u8(vLane1.val[1]);\n uint16x8_t v_el2 = vpaddlq_u8(vLane1.val[2]);\n v_el0 = vpadalq_u8(v_el0, vLane2.val[0]);\n v_el1 = vpadalq_u8(v_el1, vLane2.val[1]);\n v_el2 = vpadalq_u8(v_el2, vLane2.val[2]);\n\n v_dst0.val[0] = areaDownsamplingDivision(v_el0);\n v_dst0.val[1] = areaDownsamplingDivision(v_el1);\n v_dst0.val[2] = areaDownsamplingDivision(v_el2);\n }\n\n vLane1 = vld3q_u8(src0_row + sj + 48);\n vLane2 = vld3q_u8(src1_row + sj + 48);\n {\n uint16x8_t v_el0 = vpaddlq_u8(vLane1.val[0]);\n uint16x8_t v_el1 = vpaddlq_u8(vLane1.val[1]);\n uint16x8_t v_el2 = vpaddlq_u8(vLane1.val[2]);\n v_el0 = vpadalq_u8(v_el0, vLane2.val[0]);\n v_el1 = vpadalq_u8(v_el1, vLane2.val[1]);\n v_el2 = vpadalq_u8(v_el2, vLane2.val[2]);\n\n v_dst1.val[0] = areaDownsamplingDivision(v_el0);\n v_dst1.val[1] = areaDownsamplingDivision(v_el1);\n v_dst1.val[2] = areaDownsamplingDivision(v_el2);\n }\n\n uint8x16x3_t v_dst;\n v_dst.val[0] = vcombine_u8(v_dst0.val[0], v_dst1.val[0]);\n v_dst.val[1] = vcombine_u8(v_dst0.val[1], v_dst1.val[1]);\n v_dst.val[2] = vcombine_u8(v_dst0.val[2], v_dst1.val[2]);\n\n vst3q_u8(dst_row + dj, v_dst);\n }\n#endif\n\n for ( ; dj < roiw8; dj += 24, sj += 48)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n\n uint8x16x3_t vLane1 = vld3q_u8(src0_row + sj);\n uint8x16x3_t vLane2 = vld3q_u8(src1_row + sj);\n\n uint16x8_t v_el0 = vpaddlq_u8(vLane1.val[0]);\n uint16x8_t v_el1 = vpaddlq_u8(vLane1.val[1]);\n uint16x8_t v_el2 = vpaddlq_u8(vLane1.val[2]);\n v_el0 = vpadalq_u8(v_el0, vLane2.val[0]);\n v_el1 = vpadalq_u8(v_el1, vLane2.val[1]);\n v_el2 = vpadalq_u8(v_el2, vLane2.val[2]);\n\n uint8x8x3_t v_dst;\n v_dst.val[0] = areaDownsamplingDivision(v_el0);\n v_dst.val[1] = areaDownsamplingDivision(v_el1);\n v_dst.val[2] = areaDownsamplingDivision(v_el2);\n\n vst3_u8(dst_row + dj, v_dst);\n }\n\n for (size_t dwidth = dsize.width * 3; dj < dwidth; dj += 3, sj += 6)\n {\n dst_row[dj ] = areaDownsamplingDivision(\n (u16)src0_row[sj ] + src0_row[sj + 3] +\n src1_row[sj ] + src1_row[sj + 3]);\n dst_row[dj + 1] = areaDownsamplingDivision(\n (u16)src0_row[sj + 1] + src0_row[sj + 4] +\n src1_row[sj + 1] + src1_row[sj + 4]);\n dst_row[dj + 2] = areaDownsamplingDivision(\n (u16)src0_row[sj + 2] + src0_row[sj + 5] +\n src1_row[sj + 2] + src1_row[sj + 5]);\n }\n }\n }\n else if ((wr == 0.5f) && (hr == 0.5f))\n {\n#ifndef ANDROID\n size_t roiw32 = dsize.width >= 31 ? (dsize.width - 31) * 3 : 0;\n#endif\n size_t roiw16 = dsize.width >= 15 ? (dsize.width - 15) * 3 : 0;\n\n for (size_t i = 0; i < dsize.height; i += 2)\n {\n const u8 * src_row = internal::getRowPtr(srcBase, srcStride, i >> 1);\n u8 * dst0_row = internal::getRowPtr(dstBase, dstStride, i);\n u8 * dst1_row = internal::getRowPtr(dstBase, dstStride, std::min(i + 1, dsize.height - 1));\n size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n for ( ; dj < roiw32; dj += 96, sj += 48)\n {\n internal::prefetch(src_row + sj);\n\n uint8x16x3_t v_src = vld3q_u8(src_row + sj);\n uint8x16x2_t v_c0 = vzipq_u8(v_src.val[0], v_src.val[0]);\n uint8x16x2_t v_c1 = vzipq_u8(v_src.val[1], v_src.val[1]);\n uint8x16x2_t v_c2 = vzipq_u8(v_src.val[2], v_src.val[2]);\n\n uint8x16x3_t v_dst;\n v_dst.val[0] = v_c0.val[0];\n v_dst.val[1] = v_c1.val[0];\n v_dst.val[2] = v_c2.val[0];\n vst3q_u8(dst0_row + dj, v_dst);\n vst3q_u8(dst1_row + dj, v_dst);\n\n v_dst.val[0] = v_c0.val[1];\n v_dst.val[1] = v_c1.val[1];\n v_dst.val[2] = v_c2.val[1];\n vst3q_u8(dst0_row + dj + 48, v_dst);\n vst3q_u8(dst1_row + dj + 48, v_dst);\n }\n#endif\n\n for ( ; dj < roiw16; dj += 48, sj += 24)\n {\n internal::prefetch(src_row + sj);\n\n uint8x8x3_t v_src = vld3_u8(src_row + sj);\n uint8x8x2_t v_c0 = vzip_u8(v_src.val[0], v_src.val[0]);\n uint8x8x2_t v_c1 = vzip_u8(v_src.val[1], v_src.val[1]);\n uint8x8x2_t v_c2 = vzip_u8(v_src.val[2], v_src.val[2]);\n\n uint8x16x3_t v_dst;\n v_dst.val[0] = vcombine_u8(v_c0.val[0], v_c0.val[1]);\n v_dst.val[1] = vcombine_u8(v_c1.val[0], v_c1.val[1]);\n v_dst.val[2] = vcombine_u8(v_c2.val[0], v_c2.val[1]);\n vst3q_u8(dst0_row + dj, v_dst);\n vst3q_u8(dst1_row + dj, v_dst);\n }\n\n for (size_t dwidth = dsize.width * 3; dj < dwidth; dj += 6, sj += 3)\n {\n u8 src_val = src_row[sj];\n dst0_row[dj] = dst0_row[dj + 3] = src_val;\n dst1_row[dj] = dst1_row[dj + 3] = src_val;\n\n src_val = src_row[sj + 1];\n dst0_row[dj + 1] = dst0_row[dj + 4] = src_val;\n dst1_row[dj + 1] = dst1_row[dj + 4] = src_val;\n\n src_val = src_row[sj + 2];\n dst0_row[dj + 2] = dst0_row[dj + 5] = src_val;\n dst1_row[dj + 2] = dst1_row[dj + 5] = src_val;\n }\n }\n }\n else \/\/if ((hr == 4.0f) && (wr == 4.0f)) \/\/the only scale that lasts after isSupported check\n {\n#ifndef ANDROID\n size_t roiw8 = dsize.width >= 7 ? (dsize.width - 7) * 3 : 0;\n#endif\n\n for (size_t i = 0; i < dsize.height; ++i)\n {\n const u8 * src0_row = internal::getRowPtr(srcBase, srcStride, i << 2);\n const u8 * src1_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 1);\n const u8 * src2_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 2);\n const u8 * src3_row = internal::getRowPtr(srcBase, srcStride, (i << 2) + 3);\n u8 * dst_row = internal::getRowPtr(dstBase, dstStride, i);\n size_t sj = 0, dj = 0;\n\n#ifndef ANDROID\n for ( ; dj < roiw8; dj += 24, sj += 96)\n {\n internal::prefetch(src0_row + sj);\n internal::prefetch(src1_row + sj);\n internal::prefetch(src2_row + sj);\n internal::prefetch(src3_row + sj);\n\n uint8x16x3_t vLane10 = vld3q_u8(src0_row + sj), vLane11 = vld3q_u8(src0_row + sj + 48);\n uint8x16x3_t vLane20 = vld3q_u8(src1_row + sj), vLane21 = vld3q_u8(src1_row + sj + 48);\n uint8x16x3_t vLane30 = vld3q_u8(src2_row + sj), vLane31 = vld3q_u8(src2_row + sj + 48);\n uint8x16x3_t vLane40 = vld3q_u8(src3_row + sj), vLane41 = vld3q_u8(src3_row + sj + 48);\n\n uint8x8x3_t v_dst;\n\n \/\/ channel 0\n {\n uint16x8_t v_lane0 = vpaddlq_u8(vLane10.val[0]);\n uint16x8_t v_lane1 = vpaddlq_u8(vLane20.val[0]);\n uint16x8_t v_lane2 = vpaddlq_u8(vLane30.val[0]);\n uint16x8_t v_lane3 = vpaddlq_u8(vLane40.val[0]);\n v_lane0 = vaddq_u16(v_lane0, v_lane1);\n v_lane0 = vaddq_u16(v_lane0, v_lane2);\n v_lane0 = vaddq_u16(v_lane0, v_lane3);\n\n uint16x8_t v_lane0_ = vpaddlq_u8(vLane11.val[0]);\n uint16x8_t v_lane1_ = vpaddlq_u8(vLane21.val[0]);\n uint16x8_t v_lane2_ = vpaddlq_u8(vLane31.val[0]);\n uint16x8_t v_lane3_ = vpaddlq_u8(vLane41.val[0]);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane1_);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane2_);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane3_);\n\n v_dst.val[0] = areaDownsamplingDivision(\n vcombine_u16(vmovn_u32(vpaddlq_u16(v_lane0)),\n vmovn_u32(vpaddlq_u16(v_lane0_))));\n }\n\n \/\/ channel 1\n {\n uint16x8_t v_lane0 = vpaddlq_u8(vLane10.val[1]);\n uint16x8_t v_lane1 = vpaddlq_u8(vLane20.val[1]);\n uint16x8_t v_lane2 = vpaddlq_u8(vLane30.val[1]);\n uint16x8_t v_lane3 = vpaddlq_u8(vLane40.val[1]);\n v_lane0 = vaddq_u16(v_lane0, v_lane1);\n v_lane0 = vaddq_u16(v_lane0, v_lane2);\n v_lane0 = vaddq_u16(v_lane0, v_lane3);\n\n uint16x8_t v_lane0_ = vpaddlq_u8(vLane11.val[1]);\n uint16x8_t v_lane1_ = vpaddlq_u8(vLane21.val[1]);\n uint16x8_t v_lane2_ = vpaddlq_u8(vLane31.val[1]);\n uint16x8_t v_lane3_ = vpaddlq_u8(vLane41.val[1]);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane1_);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane2_);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane3_);\n\n v_dst.val[1] = areaDownsamplingDivision(\n vcombine_u16(vmovn_u32(vpaddlq_u16(v_lane0)),\n vmovn_u32(vpaddlq_u16(v_lane0_))));\n }\n\n \/\/ channel 2\n {\n uint16x8_t v_lane0 = vpaddlq_u8(vLane10.val[2]);\n uint16x8_t v_lane1 = vpaddlq_u8(vLane20.val[2]);\n uint16x8_t v_lane2 = vpaddlq_u8(vLane30.val[2]);\n uint16x8_t v_lane3 = vpaddlq_u8(vLane40.val[2]);\n v_lane0 = vaddq_u16(v_lane0, v_lane1);\n v_lane0 = vaddq_u16(v_lane0, v_lane2);\n v_lane0 = vaddq_u16(v_lane0, v_lane3);\n\n uint16x8_t v_lane0_ = vpaddlq_u8(vLane11.val[2]);\n uint16x8_t v_lane1_ = vpaddlq_u8(vLane21.val[2]);\n uint16x8_t v_lane2_ = vpaddlq_u8(vLane31.val[2]);\n uint16x8_t v_lane3_ = vpaddlq_u8(vLane41.val[2]);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane1_);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane2_);\n v_lane0_ = vaddq_u16(v_lane0_, v_lane3_);\n\n v_dst.val[2] = areaDownsamplingDivision(\n vcombine_u16(vmovn_u32(vpaddlq_u16(v_lane0)),\n vmovn_u32(vpaddlq_u16(v_lane0_))));\n }\n\n vst3_u8(dst_row + dj, v_dst);\n }\n#endif\n\n for (size_t dwidth = dsize.width * 3; dj < dwidth; dj += 3, sj += 12)\n {\n dst_row[dj ] = areaDownsamplingDivision(\n (u16)src0_row[sj ] + src0_row[sj + 3] +\n src0_row[sj + 6] + src0_row[sj + 9] +\n src1_row[sj ] + src1_row[sj + 3] +\n src1_row[sj + 6] + src1_row[sj + 9] +\n src2_row[sj ] + src2_row[sj + 3] +\n src2_row[sj + 6] + src2_row[sj + 9] +\n src3_row[sj ] + src3_row[sj + 3] +\n src3_row[sj + 6] + src3_row[sj + 9]);\n\n dst_row[dj + 1] = areaDownsamplingDivision(\n (u16)src0_row[sj + 1] + src0_row[sj + 4] +\n src0_row[sj + 7] + src0_row[sj + 10] +\n src1_row[sj + 1] + src1_row[sj + 4] +\n src1_row[sj + 7] + src1_row[sj + 10] +\n src2_row[sj + 1] + src2_row[sj + 4] +\n src2_row[sj + 7] + src2_row[sj + 10] +\n src3_row[sj + 1] + src3_row[sj + 4] +\n src3_row[sj + 7] + src3_row[sj + 10]);\n\n dst_row[dj + 2] = areaDownsamplingDivision(\n (u16)src0_row[sj + 2] + src0_row[sj + 5] +\n src0_row[sj + 8] + src0_row[sj + 11] +\n src1_row[sj + 2] + src1_row[sj + 5] +\n src1_row[sj + 8] + src1_row[sj + 11] +\n src2_row[sj + 2] + src2_row[sj + 5] +\n src2_row[sj + 8] + src2_row[sj + 11] +\n src3_row[sj + 2] + src3_row[sj + 5] +\n src3_row[sj + 8] + src3_row[sj + 11]);\n }\n }\n }\n }\n#else\n (void)dsize;\n (void)srcBase;\n (void)srcStride;\n (void)dstBase;\n (void)dstStride;\n (void)wr;\n (void)hr;\n#endif\n (void)ssize;\n}\n\nvoid resizeAreaOpenCV(const Size2D &ssize, const Size2D &dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr, u32 channels)\n{\n resizeAreaRounding(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr, channels);\n}\n\nvoid resizeArea(const Size2D &ssize, const Size2D &dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr, u32 channels)\n{\n resizeAreaRounding(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr, channels);\n}\n\n#ifdef CAROTENE_NEON\n\nnamespace {\n\nuint8x8_t resizeLinearStep(uint8x16_t vr1, uint8x16_t vr2,\n uint8x8_t vlutl, uint8x8_t vluth,\n float32x4_t vrw, float32x4_t vcw0, float32x4_t vcw1)\n{\n uint8x8_t vr1l = internal::vqtbl1_u8(vr1, vlutl);\n uint8x8_t vr1h = internal::vqtbl1_u8(vr1, vluth);\n uint8x8_t vr2l = internal::vqtbl1_u8(vr2, vlutl);\n uint8x8_t vr2h = internal::vqtbl1_u8(vr2, vluth);\n\n uint16x8_t v1hw = vmovl_u8(vr1h);\n uint16x8_t v2hw = vmovl_u8(vr2h);\n\n int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n float32x4_t v1L = vcvtq_f32_u32(vmovl_u16(vget_low_u16(v1hw)));\n float32x4_t v1H = vcvtq_f32_u32(vmovl_u16(vget_high_u16(v1hw)));\n float32x4_t v2L = vcvtq_f32_u32(vmovl_u16(vget_low_u16(v2hw)));\n float32x4_t v2H = vcvtq_f32_u32(vmovl_u16(vget_high_u16(v2hw)));\n\n v1L = vmlaq_f32(v1L, vcvtq_f32_s32(vmovl_s16(vget_low_s16(v1df))), vcw0);\n v1H = vmlaq_f32(v1H, vcvtq_f32_s32(vmovl_s16(vget_high_s16(v1df))), vcw1);\n v2L = vmlaq_f32(v2L, vcvtq_f32_s32(vmovl_s16(vget_low_s16(v2df))), vcw0);\n v2H = vmlaq_f32(v2H, vcvtq_f32_s32(vmovl_s16(vget_high_s16(v2df))), vcw1);\n\n float32x4_t vdiffL = vsubq_f32(v1L, v2L);\n float32x4_t vdiffH = vsubq_f32(v1H, v2H);\n\n float32x4_t vL = vmlaq_f32(v2L, vdiffL, vrw);\n float32x4_t vH = vmlaq_f32(v2H, vdiffH, vrw);\n uint16x4_t vL_ = vmovn_u32(vcvtq_u32_f32(vL));\n uint16x4_t vH_ = vmovn_u32(vcvtq_u32_f32(vH));\n return vmovn_u16(vcombine_u16(vL_, vH_));\n}\n\n} \/\/ namespace\n\nnamespace {\n\nvoid resize_bilinear_rows(const Size2D &ssize, const Size2D &dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 hr, const u8** gcols, u8* gcweight, u8* buf)\n{\n f32 scale_y_offset = 0.5f * hr - 0.5f;\n\n size_t dst_h8 = dsize.height & ~7;\n size_t dst_w8 = dsize.width & ~7;\n size_t src_w8 = ssize.width & ~7;\n\n size_t r = 0;\n for (; r < dst_h8; r += 8)\n {\nresize8u_xystretch:\n const u8* rows[16];\n u8 rweight[8];\n\n for (u32 i = 0; i < 8; ++i)\n {\n f32 w = (i + r) * hr + scale_y_offset;\n ptrdiff_t src_row = floorf(w);\n ptrdiff_t src_row2 = src_row + 1;\n\n rweight[i] = (u8)((src_row2-w) * 128);\n\n if (src_row < 0)\n src_row = 0;\n if (src_row2 >= (ptrdiff_t)ssize.height)\n src_row2 = ssize.height-1;\n\n rows[2 * i] = srcBase + src_row * srcStride;\n rows[2 * i + 1] = srcBase + src_row2 * srcStride;\n }\n\n uint8x8_t vr0w = vdup_n_u8(rweight[0]);\n uint8x8_t vr1w = vdup_n_u8(rweight[1]);\n uint8x8_t vr2w = vdup_n_u8(rweight[2]);\n uint8x8_t vr3w = vdup_n_u8(rweight[3]);\n uint8x8_t vr4w = vdup_n_u8(rweight[4]);\n uint8x8_t vr5w = vdup_n_u8(rweight[5]);\n uint8x8_t vr6w = vdup_n_u8(rweight[6]);\n uint8x8_t vr7w = vdup_n_u8(rweight[7]);\n\n uint8x8_t vr0w2 = vdup_n_u8(128 - rweight[0]);\n uint8x8_t vr1w2 = vdup_n_u8(128 - rweight[1]);\n uint8x8_t vr2w2 = vdup_n_u8(128 - rweight[2]);\n uint8x8_t vr3w2 = vdup_n_u8(128 - rweight[3]);\n uint8x8_t vr4w2 = vdup_n_u8(128 - rweight[4]);\n uint8x8_t vr5w2 = vdup_n_u8(128 - rweight[5]);\n uint8x8_t vr6w2 = vdup_n_u8(128 - rweight[6]);\n uint8x8_t vr7w2 = vdup_n_u8(128 - rweight[7]);\n\n size_t col = 0;\n for(; col < src_w8; col += 8)\n {\n internal::prefetch(rows[3] + col);\n internal::prefetch(rows[7] + col);\n internal::prefetch(rows[11] + col);\n internal::prefetch(rows[15] + col);\nresize8u_ystretch:\n uint8x8_t vsrc0l1 = vld1_u8(rows[0] + col);\n uint8x8_t vsrc0l2 = vld1_u8(rows[1] + col);\n uint8x8_t vsrc1l1 = vld1_u8(rows[2] + col);\n uint8x8_t vsrc1l2 = vld1_u8(rows[3] + col);\n\n \/\/ (l1 * w + l2 * (128 - w) + 64) \/ 128\n uint16x8_t vdst0l = vmull_u8(vsrc0l1, vr0w);\n uint16x8_t vdst1l = vmull_u8(vsrc1l1, vr1w);\n\n uint8x8_t vsrc2l1 = vld1_u8(rows[4] + col);\n uint8x8_t vsrc2l2 = vld1_u8(rows[5] + col);\n uint8x8_t vsrc3l1 = vld1_u8(rows[6] + col);\n uint8x8_t vsrc3l2 = vld1_u8(rows[7] + col);\n\n vdst0l = vmlal_u8(vdst0l, vsrc0l2, vr0w2);\n vdst1l = vmlal_u8(vdst1l, vsrc1l2, vr1w2);\n uint16x8_t vdst2l = vmull_u8(vsrc2l1, vr2w);\n uint16x8_t vdst3l = vmull_u8(vsrc3l1, vr3w);\n\n uint8x8_t vsrc4l1 = vld1_u8(rows[8] + col);\n uint8x8_t vsrc4l2 = vld1_u8(rows[9] + col);\n uint8x8_t vsrc5l1 = vld1_u8(rows[10] + col);\n uint8x8_t vsrc5l2 = vld1_u8(rows[11] + col);\n\n vdst2l = vmlal_u8(vdst2l, vsrc2l2, vr2w2);\n vdst3l = vmlal_u8(vdst3l, vsrc3l2, vr3w2);\n uint16x8_t vdst4l = vmull_u8(vsrc4l1, vr4w);\n uint16x8_t vdst5l = vmull_u8(vsrc5l1, vr5w);\n\n uint8x8_t vsrc6l1 = vld1_u8(rows[12] + col);\n uint8x8_t vsrc6l2 = vld1_u8(rows[13] + col);\n uint8x8_t vsrc7l1 = vld1_u8(rows[14] + col);\n uint8x8_t vsrc7l2 = vld1_u8(rows[15] + col);\n\n uint8x8_t vdst0 = vrshrn_n_u16(vdst0l, 7);\n uint8x8_t vdst1 = vrshrn_n_u16(vdst1l, 7);\n vdst4l = vmlal_u8(vdst4l, vsrc4l2, vr4w2);\n vdst5l = vmlal_u8(vdst5l, vsrc5l2, vr5w2);\n uint16x8_t vdst6l = vmull_u8(vsrc6l1, vr6w);\n uint16x8_t vdst7l = vmull_u8(vsrc7l1, vr7w);\n\n uint8x8_t vdst2 = vrshrn_n_u16(vdst2l, 7);\n uint8x8_t vdst3 = vrshrn_n_u16(vdst3l, 7);\n vdst6l = vmlal_u8(vdst6l, vsrc6l2, vr6w2);\n vdst7l = vmlal_u8(vdst7l, vsrc7l2, vr7w2);\n\n uint8x8_t vdst4 = vrshrn_n_u16(vdst4l, 7);\n uint8x8_t vdst5 = vrshrn_n_u16(vdst5l, 7);\n uint8x8_t vdst6 = vrshrn_n_u16(vdst6l, 7);\n uint8x8_t vdst7 = vrshrn_n_u16(vdst7l, 7);\n\n \/\/ == 8x8 matrix transpose ==\n\n \/\/00 01 02 03 04 05 06 07 d0\n \/\/10 11 12 13 14 15 16 17 d1\n \/\/20 21 22 23 24 25 26 27 d2\n \/\/30 31 32 33 34 35 36 37 d3\n \/\/40 41 42 43 44 45 46 47 d4\n \/\/50 51 52 53 54 55 56 57 d5\n \/\/60 61 62 63 64 65 66 67 d6\n \/\/70 71 72 73 74 75 76 77 d7\n\n uint8x8x2_t vdst10t = vtrn_u8(vdst0, vdst1);\n uint8x8x2_t vdst32t = vtrn_u8(vdst2, vdst3);\n uint8x8x2_t vdst54t = vtrn_u8(vdst4, vdst5);\n uint8x8x2_t vdst76t = vtrn_u8(vdst6, vdst7);\n\n uint8x16_t vd1d0 = vcombine_u8(vdst10t.val[0], vdst10t.val[1]);\n uint8x16_t vd3d2 = vcombine_u8(vdst32t.val[0], vdst32t.val[1]);\n uint8x16_t vd5d4 = vcombine_u8(vdst54t.val[0], vdst54t.val[1]);\n uint8x16_t vd7d6 = vcombine_u8(vdst76t.val[0], vdst76t.val[1]);\n\n \/\/00 10 02 12 04 14 06 16 d0\n \/\/01 11 03 13 05 15 07 17 d1\n \/\/20 30 22 32 24 34 26 36 d2\n \/\/21 31 23 33 25 35 27 37 d3\n \/\/40 50 42 52 44 54 46 56 d4\n \/\/41 51 43 53 45 55 47 57 d5\n \/\/60 70 62 72 64 74 66 76 d6\n \/\/61 71 63 73 65 75 67 77 d7\n\n uint16x8x2_t vq1q0t = vtrnq_u16((uint16x8_t)vd1d0, (uint16x8_t)vd3d2);\n uint16x8x2_t vq3q2t = vtrnq_u16((uint16x8_t)vd5d4, (uint16x8_t)vd7d6);\n\n \/\/00 10 20 30 04 14 24 34 d0\n \/\/01 11 21 31 05 15 25 35 d1\n \/\/02 12 22 32 06 16 26 36 d2\n \/\/03 13 23 33 07 17 27 37 d3\n \/\/40 50 60 70 44 54 64 74 d4\n \/\/41 51 61 71 45 55 65 75 d5\n \/\/42 52 62 72 46 56 66 76 d6\n \/\/43 53 63 73 47 57 67 77 d7\n\n uint32x4x2_t vq2q0t = vtrnq_u32((uint32x4_t)vq1q0t.val[0], (uint32x4_t)vq3q2t.val[0]);\n uint32x4x2_t vq3q1t = vtrnq_u32((uint32x4_t)vq1q0t.val[1], (uint32x4_t)vq3q2t.val[1]);\n\n \/\/00 10 20 30 40 50 60 70 d0\n \/\/01 11 21 31 41 51 61 71 d1\n \/\/02 12 22 32 42 52 62 72 d2\n \/\/03 13 23 33 43 53 63 73 d3\n \/\/04 14 24 34 44 54 64 74 d4\n \/\/05 15 25 35 45 55 65 75 d5\n \/\/06 16 26 36 46 56 66 76 d6\n \/\/07 17 27 37 47 57 67 77 d7\n\n vst1q_u8(buf + col * 8 + 0, (uint8x16_t)vq2q0t.val[0]);\n vst1q_u8(buf + col * 8 + 16, (uint8x16_t)vq3q1t.val[0]);\n vst1q_u8(buf + col * 8 + 32, (uint8x16_t)vq2q0t.val[1]);\n vst1q_u8(buf + col * 8 + 48, (uint8x16_t)vq3q1t.val[1]);\n }\n\n if (col < ssize.width)\n {\n col = ssize.width - 8;\n goto resize8u_ystretch;\n }\n\n u8* dst_data = dstBase + r * dstStride;\n const u8** cols = gcols;\n u8* cweight = gcweight;\n\n size_t dcol = 0;\n for (; dcol < dst_w8; dcol += 8, cols += 16, cweight += 8)\n {\n internal::prefetch(cols[0], 64*4);\nresize8u_xstretch:\n uint8x8_t vc0w = vdup_n_u8(cweight[0]);\n uint8x8_t vc1w = vdup_n_u8(cweight[1]);\n uint8x8_t vc2w = vdup_n_u8(cweight[2]);\n uint8x8_t vc3w = vdup_n_u8(cweight[3]);\n uint8x8_t vc4w = vdup_n_u8(cweight[4]);\n uint8x8_t vc5w = vdup_n_u8(cweight[5]);\n uint8x8_t vc6w = vdup_n_u8(cweight[6]);\n uint8x8_t vc7w = vdup_n_u8(cweight[7]);\n\n uint8x8_t vc0w2 = vdup_n_u8(128 - cweight[0]);\n uint8x8_t vc1w2 = vdup_n_u8(128 - cweight[1]);\n uint8x8_t vc2w2 = vdup_n_u8(128 - cweight[2]);\n uint8x8_t vc3w2 = vdup_n_u8(128 - cweight[3]);\n uint8x8_t vc4w2 = vdup_n_u8(128 - cweight[4]);\n uint8x8_t vc5w2 = vdup_n_u8(128 - cweight[5]);\n uint8x8_t vc6w2 = vdup_n_u8(128 - cweight[6]);\n uint8x8_t vc7w2 = vdup_n_u8(128 - cweight[7]);\n\n uint8x8_t vsrc0l1 = vld1_u8(cols[0]);\n uint8x8_t vsrc0l2 = vld1_u8(cols[1]);\n uint8x8_t vsrc1l1 = vld1_u8(cols[2]);\n uint8x8_t vsrc1l2 = vld1_u8(cols[3]);\n uint8x8_t vsrc2l1 = vld1_u8(cols[4]);\n uint8x8_t vsrc2l2 = vld1_u8(cols[5]);\n uint8x8_t vsrc3l1 = vld1_u8(cols[6]);\n uint8x8_t vsrc3l2 = vld1_u8(cols[7]);\n uint8x8_t vsrc4l1 = vld1_u8(cols[8]);\n uint8x8_t vsrc4l2 = vld1_u8(cols[9]);\n uint8x8_t vsrc5l1 = vld1_u8(cols[10]);\n uint8x8_t vsrc5l2 = vld1_u8(cols[11]);\n uint8x8_t vsrc6l1 = vld1_u8(cols[12]);\n uint8x8_t vsrc6l2 = vld1_u8(cols[13]);\n uint8x8_t vsrc7l1 = vld1_u8(cols[14]);\n uint8x8_t vsrc7l2 = vld1_u8(cols[15]);\n\n \/\/ (l1 * w + l2 * (128 - w) + 64) \/ 128\n uint16x8_t vdst0l = vmull_u8(vsrc0l1, vc0w);\n uint16x8_t vdst1l = vmull_u8(vsrc1l1, vc1w);\n uint16x8_t vdst2l = vmull_u8(vsrc2l1, vc2w);\n uint16x8_t vdst3l = vmull_u8(vsrc3l1, vc3w);\n uint16x8_t vdst4l = vmull_u8(vsrc4l1, vc4w);\n uint16x8_t vdst5l = vmull_u8(vsrc5l1, vc5w);\n uint16x8_t vdst6l = vmull_u8(vsrc6l1, vc6w);\n uint16x8_t vdst7l = vmull_u8(vsrc7l1, vc7w);\n\n vdst0l = vmlal_u8(vdst0l, vsrc0l2, vc0w2);\n vdst1l = vmlal_u8(vdst1l, vsrc1l2, vc1w2);\n vdst2l = vmlal_u8(vdst2l, vsrc2l2, vc2w2);\n vdst3l = vmlal_u8(vdst3l, vsrc3l2, vc3w2);\n vdst4l = vmlal_u8(vdst4l, vsrc4l2, vc4w2);\n vdst5l = vmlal_u8(vdst5l, vsrc5l2, vc5w2);\n vdst6l = vmlal_u8(vdst6l, vsrc6l2, vc6w2);\n vdst7l = vmlal_u8(vdst7l, vsrc7l2, vc7w2);\n\n uint8x8_t vdst0 = vrshrn_n_u16(vdst0l, 7);\n uint8x8_t vdst1 = vrshrn_n_u16(vdst1l, 7);\n uint8x8_t vdst2 = vrshrn_n_u16(vdst2l, 7);\n uint8x8_t vdst3 = vrshrn_n_u16(vdst3l, 7);\n uint8x8_t vdst4 = vrshrn_n_u16(vdst4l, 7);\n uint8x8_t vdst5 = vrshrn_n_u16(vdst5l, 7);\n uint8x8_t vdst6 = vrshrn_n_u16(vdst6l, 7);\n uint8x8_t vdst7 = vrshrn_n_u16(vdst7l, 7);\n\n \/\/ == 8x8 matrix transpose ==\n uint8x8x2_t vdst10t = vtrn_u8(vdst0, vdst1);\n uint8x8x2_t vdst32t = vtrn_u8(vdst2, vdst3);\n uint8x8x2_t vdst54t = vtrn_u8(vdst4, vdst5);\n uint8x8x2_t vdst76t = vtrn_u8(vdst6, vdst7);\n uint8x16_t vd1d0 = vcombine_u8(vdst10t.val[0], vdst10t.val[1]);\n uint8x16_t vd3d2 = vcombine_u8(vdst32t.val[0], vdst32t.val[1]);\n uint8x16_t vd5d4 = vcombine_u8(vdst54t.val[0], vdst54t.val[1]);\n uint8x16_t vd7d6 = vcombine_u8(vdst76t.val[0], vdst76t.val[1]);\n uint16x8x2_t vq1q0t = vtrnq_u16((uint16x8_t)vd1d0, (uint16x8_t)vd3d2);\n uint16x8x2_t vq3q2t = vtrnq_u16((uint16x8_t)vd5d4, (uint16x8_t)vd7d6);\n uint32x4x2_t vq2q0t = vtrnq_u32((uint32x4_t)vq1q0t.val[0], (uint32x4_t)vq3q2t.val[0]);\n uint32x4x2_t vq3q1t = vtrnq_u32((uint32x4_t)vq1q0t.val[1], (uint32x4_t)vq3q2t.val[1]);\n\n \/\/save results\n vst1_u8(dst_data + 0 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq2q0t.val[0]));\n vst1_u8(dst_data + 1 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq2q0t.val[0]));\n vst1_u8(dst_data + 2 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq3q1t.val[0]));\n vst1_u8(dst_data + 3 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq3q1t.val[0]));\n vst1_u8(dst_data + 4 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq2q0t.val[1]));\n vst1_u8(dst_data + 5 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq2q0t.val[1]));\n vst1_u8(dst_data + 6 * dstStride + dcol, (uint8x8_t)vget_low_u32(vq3q1t.val[1]));\n vst1_u8(dst_data + 7 * dstStride + dcol, (uint8x8_t)vget_high_u32(vq3q1t.val[1]));\n }\n\n if (dcol < dsize.width)\n {\n dcol = dsize.width - 8;\n cols = gcols + dcol * 2;\n cweight = gcweight + dcol;\n goto resize8u_xstretch;\n }\n }\n\n if (r < dsize.height)\n {\n r = dsize.height - 8;\n goto resize8u_xystretch;\n }\n}\n\ntemplate struct resizeLinearInternals;\ntemplate <> struct resizeLinearInternals<1>\n{\n int32x4_t vc_upd;\n int32x4_t vc0;\n int32x4_t vcmax;\n\n inline resizeLinearInternals(int32x4_t & vi, u32 srccols)\n {\n vc_upd = vdupq_n_s32(4);\n vc0 = vdupq_n_s32(0);\n vcmax = vdupq_n_s32(srccols-1);\n\n s32 tmp0123[] = {0, 1, 2, 3 };\n vi = vld1q_s32(tmp0123);\n }\n inline void updateIndexes(int32x4_t & vi, int32x4_t & vsrch, int32x4_t & vsrcl)\n {\n vsrch = vminq_s32(vsrch, vcmax);\n vsrcl = vmaxq_s32(vsrcl, vc0);\n vsrcl = vminq_s32(vsrcl, vcmax);\/\/for safe tail\n vsrch = vshlq_n_s32(vsrch, 3);\n vsrcl = vshlq_n_s32(vsrcl, 3);\n vi = vaddq_s32(vi, vc_upd);\n }\n};\ntemplate <> struct resizeLinearInternals<4>\n{\n int32x4_t vc_upd;\n int32x4_t vc0;\n int32x4_t vcmax;\n int32x4_t v0123x8;\n\n inline resizeLinearInternals(int32x4_t & vi, u32 srccols)\n {\n vc_upd = vdupq_n_s32(1);\n vc0 = vdupq_n_s32(0);\n vcmax = vdupq_n_s32(srccols-1);\n s32 tmp0123x8[] = {0, 8, 16, 24};\n v0123x8 = vld1q_s32(tmp0123x8);\n\n vi = vc0;\n }\n inline void updateIndexes(int32x4_t & vi, int32x4_t & vsrch, int32x4_t & vsrcl)\n {\n vsrch = vminq_s32(vsrch, vcmax);\n vsrcl = vmaxq_s32(vsrcl, vc0);\n vsrch = vshlq_n_s32(vsrch, 5);\n vsrcl = vshlq_n_s32(vsrcl, 5);\n vsrch = vaddq_s32(vsrch, v0123x8);\n vsrcl = vaddq_s32(vsrcl, v0123x8);\n vi = vaddq_s32(vi, vc_upd);\n }\n};\n\ntemplate \nvoid resizeLinearOpenCVchan(const Size2D &_ssize, const Size2D &_dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr)\n{\n float scale_x_offset = 0.5f * wr - 0.5f;\n\n Size2D ssize(_ssize.width*channels, _ssize.height);\n Size2D dsize(_dsize.width*channels, _dsize.height);\n\n std::vector gcweight((dsize.width + 7) & ~7);\n std::vector gcols(((dsize.width + 7) & ~7) * 2);\n std::vector buf(((ssize.width + 7) & ~7) * 8); \/\/ (8 rows) x (width of src)\n\n float32x4_t vscale_x = vdupq_n_f32(wr);\n float32x4_t vscale_x_offset = vdupq_n_f32(scale_x_offset);\n int32x4_t vc1 = vdupq_n_s32(1);\n float32x4_t vc128f = vdupq_n_f32(128.0f);\n\n int32x4_t vi;\n resizeLinearInternals indexes(vi, _ssize.width);\/\/u32 is used to store indexes\n \/\/so we could get issues on src image dimensions greater than (2^32-1)\n\n for (size_t dcol = 0; dcol < dsize.width; dcol += 8)\n {\n s32 idx[16];\n\n float32x4_t vif = vcvtq_f32_s32(vi);\n float32x4_t vw = vmlaq_f32(vscale_x_offset, vscale_x, vif);\n int32x4_t vwi = vcvtq_s32_f32(vw);\n float32x4_t vwif = vcvtq_f32_s32(vwi);\n int32x4_t vmask = (int32x4_t)vcltq_f32(vwif, vw);\n int32x4_t vsrch = vsubq_s32(vwi, vmask);\n int32x4_t vsrcl = vsubq_s32(vsrch, vc1);\n float32x4_t vsrchf = vcvtq_f32_s32(vsrch);\n float32x4_t vw2 = vsubq_f32(vsrchf, vw);\n\n vw2 = vmulq_f32(vw2, vc128f);\n uint32x4_t vw32u = vcvtq_u32_f32(vw2);\n uint16x4_t vw16ul = vmovn_u32(vw32u);\n indexes.updateIndexes(vi, vsrch, vsrcl);\n\n vst1q_s32(idx + 0, vsrcl);\n vst1q_s32(idx + 8, vsrch);\n\n vif = vcvtq_f32_s32(vi);\n vw = vmlaq_f32(vscale_x_offset, vscale_x, vif);\n vwi = vcvtq_s32_f32(vw);\n vwif = vcvtq_f32_s32(vwi);\n vmask = (int32x4_t)vcltq_f32(vwif, vw);\n vsrch = vsubq_s32(vwi, vmask);\n vsrcl = vsubq_s32(vsrch, vc1);\n vsrchf = vcvtq_f32_s32(vsrch);\n vw2 = vsubq_f32(vsrchf, vw);\n\n vw2 = vmulq_f32(vw2, vc128f);\n vw32u = vcvtq_u32_f32(vw2);\n indexes.updateIndexes(vi, vsrch, vsrcl);\n\n uint16x4_t vw16uh = vmovn_u32(vw32u);\n\n vst1q_s32(idx + 4, vsrcl);\n vst1q_s32(idx + 12, vsrch);\n\n uint8x8_t vw8u = vmovn_u16(vcombine_u16(vw16ul, vw16uh));\n\n for (u32 i = 0; i < 8; ++i)\n {\n gcols[dcol * 2 + i*2] = &buf[idx[i]];\n gcols[dcol * 2 + i*2 + 1] = &buf[idx[i + 8]];\n }\n\n vst1_u8(&gcweight[dcol], vw8u);\n }\n\n resize_bilinear_rows(ssize, dsize, srcBase, srcStride, dstBase, dstStride, hr, &gcols[0], &gcweight[0], &buf[0]);\n}\n\nvoid downsample_bilinear_8uc1(const Size2D &ssize, const Size2D &dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr)\n{\n internal::assertSupportedConfiguration(wr <= 2.f && hr <= 2.f);\n\n enum { SHIFT_BITS = 11 };\n\n f32 scale_x_offset = 0.5f * wr - 0.5f;\n f32 scale_y_offset = 0.5f * hr - 0.5f;\n\n std::vector _buf(dsize.height*(2*(sizeof(ptrdiff_t)\/sizeof(s32))+1)+1);\n ptrdiff_t* buf = (ptrdiff_t*)&_buf[0];\n s32* buf2 = (s32*)buf+2*(sizeof(ptrdiff_t)\/sizeof(s32))*dsize.height;\n for(size_t row = 0; row < (size_t)dsize.height; ++row)\n {\n f32 r = row * hr + scale_y_offset;\n ptrdiff_t src_row = floorf(r);\n ptrdiff_t src_row2 = src_row + 1;\n\n f32 rweight = src_row2 - r;\n buf2[row] = floorf(rweight * (1 << SHIFT_BITS) + 0.5f);\n buf[0 * dsize.height + row] = std::max(0, src_row);\n buf[1 * dsize.height + row] = std::min((ptrdiff_t)ssize.height-1, src_row2);\n }\n\n#define USE_CORRECT_VERSION 0\n\n ptrdiff_t col = 0;\n\/***********************************************\/\n for(; col <= (ptrdiff_t)dsize.width-16; col+=16)\n {\n ptrdiff_t col1[16];\n ptrdiff_t col2[16];\n s16 cwi[16];\n\n for(s32 k = 0; k < 16; ++k)\n {\n f32 c = (col + k) * wr + scale_x_offset;\n col1[k] = (ptrdiff_t)c;\n col2[k] = col1[k] + 1;\n\n cwi[k] = (short)floorf((col2[k] - c) * (1 << SHIFT_BITS) + 0.5f);\n\n if(col1[k] < 0) col1[k] = 0;\n if(col2[k] >= (ptrdiff_t)ssize.width) col2[k] = ssize.width-1;\n }\n\n ptrdiff_t x = std::min(col1[0], (ptrdiff_t)ssize.width-16);\n ptrdiff_t y = std::min(col1[8], (ptrdiff_t)ssize.width-16);\n u8 lutl[16];\n u8 luth[16];\n for(s32 k = 0; k < 8; ++k)\n {\n lutl[k] = (u8)(col1[k] - x);\n luth[k] = (u8)(col2[k] - x);\n lutl[k+8] = (u8)(col1[k+8] - y);\n luth[k+8] = (u8)(col2[k+8] - y);\n }\n\n uint8x8_t vlutl = vld1_u8(lutl);\n uint8x8_t vluth = vld1_u8(luth);\n int16x8_t vcw = vld1q_s16(cwi);\n\n uint8x8_t vlutl_ = vld1_u8(lutl+8);\n uint8x8_t vluth_ = vld1_u8(luth+8);\n int16x8_t vcw_ = vld1q_s16(cwi+8);\n\n for(ptrdiff_t row = 0; row < (ptrdiff_t)dsize.height; ++row)\n {\n#if USE_CORRECT_VERSION\n int32x4_t vrw = vdupq_n_s32(buf2[row]);\n#else\n int16x8_t vrw = vdupq_n_s16((int16_t)buf2[row]);\n int16x8_t vrW = vdupq_n_s16((int16_t)((1 << SHIFT_BITS) - buf2[row]));\n#endif\n\n internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 2*srcStride);\n internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 3*srcStride);\n\n {\n union { uint8x16_t v; uint8x8x2_t w; } vr1 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[0*dsize.height + row]) + x) };\n union { uint8x16_t v; uint8x8x2_t w; } vr2 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x) };\n\n uint8x8_t vr1l = vtbl2_u8(vr1.w, vlutl);\n uint8x8_t vr1h = vtbl2_u8(vr1.w, vluth);\n uint8x8_t vr2l = vtbl2_u8(vr2.w, vlutl);\n uint8x8_t vr2h = vtbl2_u8(vr2.w, vluth);\n\n uint16x8_t v1hw = vmovl_u8(vr1h);\n uint16x8_t v2hw = vmovl_u8(vr2h);\n\n int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n int32x4_t v1L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v1hw), SHIFT_BITS));\n int32x4_t v1H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v1hw), SHIFT_BITS));\n int32x4_t v2L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v2hw), SHIFT_BITS));\n int32x4_t v2H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v2hw), SHIFT_BITS));\n\n v1L = vmlal_s16(v1L, vget_low_s16(v1df), vget_low_s16(vcw));\n v1H = vmlal_s16(v1H, vget_high_s16(v1df), vget_high_s16(vcw));\n v2L = vmlal_s16(v2L, vget_low_s16(v2df), vget_low_s16(vcw));\n v2H = vmlal_s16(v2H, vget_high_s16(v2df), vget_high_s16(vcw));\n\n#if USE_CORRECT_VERSION\n \/* correct version *\/\n int32x4_t vL = vshlq_n_s32(v2L, SHIFT_BITS);\n int32x4_t vH = vshlq_n_s32(v2H, SHIFT_BITS);\n int32x4_t vdiffL = vsubq_s32(v1L, v2L);\n int32x4_t vdiffH = vsubq_s32(v1H, v2H);\n\n vL = vmlaq_s32(vL, vdiffL, vrw);\n vH = vmlaq_s32(vH, vdiffH, vrw);\n uint16x4_t vL_ = vqrshrun_n_s32(vL, 2*SHIFT_BITS - 8);\n uint16x4_t vH_ = vqrshrun_n_s32(vH, 2*SHIFT_BITS - 8);\n uint8x8_t vres = vrshrn_n_u16(vcombine_u16(vL_, vH_), 8);\n vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#else\n \/* ugly version matching to OpenCV's SSE optimization *\/\n int16x4_t v1Ls = vshrn_n_s32(v1L, 4);\n int16x4_t v1Hs = vshrn_n_s32(v1H, 4);\n int16x4_t v2Ls = vshrn_n_s32(v2L, 4);\n int16x4_t v2Hs = vshrn_n_s32(v2H, 4);\n\n int16x8_t v1s = vqdmulhq_s16(vcombine_s16(v1Ls, v1Hs), vrw);\n int16x8_t v2s = vqdmulhq_s16(vcombine_s16(v2Ls, v2Hs), vrW);\n\n int16x8_t vsum = vaddq_s16(vshrq_n_s16(v1s,1), vshrq_n_s16(v2s,1));\n uint8x8_t vres = vqrshrun_n_s16(vsum, 2);\n\n vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#endif\n }\n\n {\n union { uint8x16_t v; uint8x8x2_t w; } vr1 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[0*dsize.height + row]) + y) };\n union { uint8x16_t v; uint8x8x2_t w; } vr2 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + y) };\n\n uint8x8_t vr1l = vtbl2_u8(vr1.w, vlutl_);\n uint8x8_t vr1h = vtbl2_u8(vr1.w, vluth_);\n uint8x8_t vr2l = vtbl2_u8(vr2.w, vlutl_);\n uint8x8_t vr2h = vtbl2_u8(vr2.w, vluth_);\n\n uint16x8_t v1hw = vmovl_u8(vr1h);\n uint16x8_t v2hw = vmovl_u8(vr2h);\n\n int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n int32x4_t v1L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v1hw), SHIFT_BITS));\n int32x4_t v1H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v1hw), SHIFT_BITS));\n int32x4_t v2L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v2hw), SHIFT_BITS));\n int32x4_t v2H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v2hw), SHIFT_BITS));\n\n v1L = vmlal_s16(v1L, vget_low_s16(v1df), vget_low_s16(vcw_));\n v1H = vmlal_s16(v1H, vget_high_s16(v1df), vget_high_s16(vcw_));\n v2L = vmlal_s16(v2L, vget_low_s16(v2df), vget_low_s16(vcw_));\n v2H = vmlal_s16(v2H, vget_high_s16(v2df), vget_high_s16(vcw_));\n\n#if USE_CORRECT_VERSION\n \/* correct version *\/\n int32x4_t vL = vshlq_n_s32(v2L, SHIFT_BITS);\n int32x4_t vH = vshlq_n_s32(v2H, SHIFT_BITS);\n int32x4_t vdiffL = vsubq_s32(v1L, v2L);\n int32x4_t vdiffH = vsubq_s32(v1H, v2H);\n\n vL = vmlaq_s32(vL, vdiffL, vrw);\n vH = vmlaq_s32(vH, vdiffH, vrw);\n uint16x4_t vL_ = vqrshrun_n_s32(vL, 2*SHIFT_BITS - 8);\n uint16x4_t vH_ = vqrshrun_n_s32(vH, 2*SHIFT_BITS - 8);\n uint8x8_t vres = vrshrn_n_u16(vcombine_u16(vL_, vH_), 8);\n vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col + 8, vres);\n#else\n \/* ugly version matching to OpenCV's SSE optimization *\/\n int16x4_t v1Ls = vshrn_n_s32(v1L, 4);\n int16x4_t v1Hs = vshrn_n_s32(v1H, 4);\n int16x4_t v2Ls = vshrn_n_s32(v2L, 4);\n int16x4_t v2Hs = vshrn_n_s32(v2H, 4);\n\n int16x8_t v1s = vqdmulhq_s16(vcombine_s16(v1Ls, v1Hs), vrw);\n int16x8_t v2s = vqdmulhq_s16(vcombine_s16(v2Ls, v2Hs), vrW);\n\n int16x8_t vsum = vaddq_s16(vshrq_n_s16(v1s,1), vshrq_n_s16(v2s,1));\n uint8x8_t vres = vqrshrun_n_s16(vsum, 2);\n\n vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col + 8, vres);\n#endif\n }\n }\n }\n\/***********************************************\/\n for(; col <= (ptrdiff_t)dsize.width-8; col+=8)\n {\ndownsample_bilinear_8uc1_col_loop8:\n ptrdiff_t col1[8];\n ptrdiff_t col2[8];\n s16 cwi[8];\n\n for(s32 k = 0; k < 8; ++k)\n {\n f32 c = (col + k) * wr + scale_x_offset;\n col1[k] = (ptrdiff_t)c;\n col2[k] = col1[k] + 1;\n\n cwi[k] = (s16)floorf((col2[k] - c) * (1 << SHIFT_BITS) + 0.5f);\n\n if(col1[k] < 0) col1[k] = 0;\n if(col2[k] >= (ptrdiff_t)ssize.width) col2[k] = (ptrdiff_t)ssize.width-1;\n }\n\n ptrdiff_t x = std::min(col1[0], (ptrdiff_t)ssize.width-16);\n u8 lutl[8];\n u8 luth[8];\n for(s32 k = 0; k < 8; ++k)\n {\n lutl[k] = (u8)(col1[k] - x);\n luth[k] = (u8)(col2[k] - x);\n }\n\n uint8x8_t vlutl = vld1_u8(lutl);\n uint8x8_t vluth = vld1_u8(luth);\n int16x8_t vcw = vld1q_s16(cwi);\n\n for(ptrdiff_t row = 0; row < (ptrdiff_t)dsize.height; ++row)\n {\n#if USE_CORRECT_VERSION\n int32x4_t vrw = vdupq_n_s32(buf2[row]);\n#else\n int16x8_t vrw = vdupq_n_s16((int16_t)buf2[row]);\n int16x8_t vrW = vdupq_n_s16((int16_t)((1 << SHIFT_BITS) - buf2[row]));\n#endif\n\n internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 2*srcStride);\n internal::prefetch(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x, 3*srcStride);\n\n union { uint8x16_t v; uint8x8x2_t w; } vr1 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[0*dsize.height + row]) + x) };\n union { uint8x16_t v; uint8x8x2_t w; } vr2 = { vld1q_u8(internal::getRowPtr(srcBase, srcStride, buf[1*dsize.height + row]) + x) };\n\n uint8x8_t vr1l = vtbl2_u8(vr1.w, vlutl);\n uint8x8_t vr1h = vtbl2_u8(vr1.w, vluth);\n uint8x8_t vr2l = vtbl2_u8(vr2.w, vlutl);\n uint8x8_t vr2h = vtbl2_u8(vr2.w, vluth);\n\n uint16x8_t v1hw = vmovl_u8(vr1h);\n uint16x8_t v2hw = vmovl_u8(vr2h);\n\n int16x8_t v1df = vreinterpretq_s16_u16(vsubl_u8(vr1l, vr1h));\n int16x8_t v2df = vreinterpretq_s16_u16(vsubl_u8(vr2l, vr2h));\n\n int32x4_t v1L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v1hw), SHIFT_BITS));\n int32x4_t v1H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v1hw), SHIFT_BITS));\n int32x4_t v2L = vreinterpretq_s32_u32(vshll_n_u16(vget_low_u16(v2hw), SHIFT_BITS));\n int32x4_t v2H = vreinterpretq_s32_u32(vshll_n_u16(vget_high_u16(v2hw), SHIFT_BITS));\n\n v1L = vmlal_s16(v1L, vget_low_s16(v1df), vget_low_s16(vcw));\n v1H = vmlal_s16(v1H, vget_high_s16(v1df), vget_high_s16(vcw));\n v2L = vmlal_s16(v2L, vget_low_s16(v2df), vget_low_s16(vcw));\n v2H = vmlal_s16(v2H, vget_high_s16(v2df), vget_high_s16(vcw));\n\n#if USE_CORRECT_VERSION\n \/* correct version *\/\n int32x4_t vL = vshlq_n_s32(v2L, SHIFT_BITS);\n int32x4_t vH = vshlq_n_s32(v2H, SHIFT_BITS);\n int32x4_t vdiffL = vsubq_s32(v1L, v2L);\n int32x4_t vdiffH = vsubq_s32(v1H, v2H);\n\n vL = vmlaq_s32(vL, vdiffL, vrw);\n vH = vmlaq_s32(vH, vdiffH, vrw);\n uint16x4_t vL_ = vqrshrun_n_s32(vL, 2*SHIFT_BITS - 8);\n uint16x4_t vH_ = vqrshrun_n_s32(vH, 2*SHIFT_BITS - 8);\n uint8x8_t vres = vrshrn_n_u16(vcombine_u16(vL_, vH_), 8);\n vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#else\n \/* ugly version matching to OpenCV's SSE optimization *\/\n int16x4_t v1Ls = vshrn_n_s32(v1L, 4);\n int16x4_t v1Hs = vshrn_n_s32(v1H, 4);\n int16x4_t v2Ls = vshrn_n_s32(v2L, 4);\n int16x4_t v2Hs = vshrn_n_s32(v2H, 4);\n\n int16x8_t v1s = vqdmulhq_s16(vcombine_s16(v1Ls, v1Hs), vrw);\n int16x8_t v2s = vqdmulhq_s16(vcombine_s16(v2Ls, v2Hs), vrW);\n\n int16x8_t vsum = vaddq_s16(vshrq_n_s16(v1s,1), vshrq_n_s16(v2s,1));\n uint8x8_t vres = vqrshrun_n_s16(vsum, 2);\n\n vst1_u8(internal::getRowPtr(dstBase, dstStride, row) + col, vres);\n#endif\n }\n }\n if (col < (ptrdiff_t)dsize.width)\n {\n col = dsize.width - 8;\n goto downsample_bilinear_8uc1_col_loop8;\n }\n}\n\n} \/\/ namespace\n\n#endif\n\nvoid resizeLinearOpenCV(const Size2D &ssize, const Size2D &dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr, u32 channels)\n{\n internal::assertSupportedConfiguration(wr > 0 && hr > 0 &&\n (dsize.width - 0.5) * wr - 0.5 < ssize.width &&\n (dsize.height - 0.5) * hr - 0.5 < ssize.height && \/\/ Ensure we have enough source data\n (dsize.width + 0.5) * wr + 0.5 >= ssize.width &&\n (dsize.height + 0.5) * hr + 0.5 >= ssize.height && \/\/ Ensure source isn't too big\n isResizeLinearOpenCVSupported(ssize, dsize, channels));\n#ifdef CAROTENE_NEON\n if(1 == channels)\n {\n if (wr <= 1.f && hr <= 1.f)\n resizeLinearOpenCVchan<1>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n else if (wr <= 2.0f && hr <= 2.0f && ssize.width >= 16)\n downsample_bilinear_8uc1(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n else\n resizeLinearOpenCVchan<1>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n }\n else if(4 == channels)\n resizeLinearOpenCVchan<4>(ssize, dsize, srcBase, srcStride, dstBase, dstStride, wr, hr);\n#else\n (void)ssize;\n (void)dsize;\n (void)srcBase;\n (void)srcStride;\n (void)dstBase;\n (void)dstStride;\n (void)wr;\n (void)hr;\n (void)channels;\n#endif\n}\n\nvoid resizeLinear(const Size2D &ssize, const Size2D &dsize,\n const u8 * srcBase, ptrdiff_t srcStride,\n u8 * dstBase, ptrdiff_t dstStride,\n f32 wr, f32 hr, u32 channels)\n{\n internal::assertSupportedConfiguration(wr > 0 && hr > 0 &&\n (dsize.width - 0.5) * wr - 0.5 < ssize.width &&\n (dsize.height - 0.5) * hr - 0.5 < ssize.height && \/\/ Ensure we have enough source data\n (dsize.width + 0.5) * wr + 0.5 >= ssize.width &&\n (dsize.height + 0.5) * hr + 0.5 >= ssize.height && \/\/ Ensure source isn't too big\n isResizeLinearSupported(ssize, dsize,\n wr, hr, channels));\n#ifdef CAROTENE_NEON\n f32 scale_x = wr;\n f32 scale_x_offset = 0.5f * scale_x - 0.5f;\n f32 scale_y = hr;\n f32 scale_y_offset = 0.5f * scale_y - 0.5f;\n\n std::vector _buf(dsize.height * 3 + 1);\n std::vector coeff(dsize.height);\n ptrdiff_t * buf = &_buf[0];\n\n for (size_t row = 0; row < dsize.height; ++row)\n {\n f32 r = row * scale_y + scale_y_offset;\n ptrdiff_t src_row = floorf(r);\n ptrdiff_t src_row2 = src_row + 1;\n\n f32 rweight = src_row2 - r;\n buf[0 * dsize.height + row] = std::max(0, src_row);\n buf[1 * dsize.height + row] = std::min(ssize.height - 1, src_row2);\n coeff[row] = rweight;\n }\n\n size_t col = 0;\n for ( ; col + 16 <= dsize.width; col += 16)\n {\n ptrdiff_t col1[16], col2[16];\n f32 cwi[16];\n\n for(s32 k = 0; k < 16; ++k)\n {\n f32 c = (col + k) * scale_x + scale_x_offset;\n col1[k] = floorf(c);\n col2[k] = col1[k] + 1;\n\n cwi[k] = col2[k] - c;\n\n if (col1[k] < 0)\n col1[k] = 0;\n if (col2[k] >= (ptrdiff_t)ssize.width)\n col2[k] = ssize.width - 1;\n }\n\n ptrdiff_t x = std::min(col1[0], ssize.width - 16);\n ptrdiff_t y = std::min(col1[8], ssize.width - 16);\n u8 lutl[16], luth[16];\n\n for (s32 k = 0; k < 8; ++k)\n {\n lutl[k] = (u8)(col1[k] - x);\n luth[k] = (u8)(col2[k] - x);\n lutl[k + 8] = (u8)(col1[k + 8] - y);\n luth[k + 8] = (u8)(col2[k + 8] - y);\n }\n\n uint8x8_t vlutl = vld1_u8(lutl);\n uint8x8_t vluth = vld1_u8(luth);\n float32x4_t vcw0 = vld1q_f32(cwi);\n float32x4_t vcw1 = vld1q_f32(cwi + 4);\n\n uint8x8_t vlutl_ = vld1_u8(lutl + 8);\n uint8x8_t vluth_ = vld1_u8(luth + 8);\n float32x4_t vcw0_ = vld1q_f32(cwi + 8);\n float32x4_t vcw1_ = vld1q_f32(cwi + 12);\n\n if (channels == 1)\n {\n for (size_t row = 0; row < dsize.height; ++row)\n {\n float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n internal::prefetch(srow0 + x + 2 * srcStride);\n internal::prefetch(srow1 + x + 2 * srcStride);\n\n uint8x8_t vres0 = resizeLinearStep(vld1q_u8(srow0 + x), vld1q_u8(srow1 + x),\n vlutl, vluth,\n vrw, vcw0, vcw1);\n\n uint8x8_t vres1 = resizeLinearStep(vld1q_u8(srow0 + y), vld1q_u8(srow1 + y),\n vlutl_, vluth_,\n vrw, vcw0_, vcw1_);\n\n vst1q_u8(drow + col, vcombine_u8(vres0, vres1));\n }\n }\n else if (channels == 3)\n {\n for (size_t row = 0; row < dsize.height; ++row)\n {\n float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n internal::prefetch(srow0 + x + 2 * srcStride);\n internal::prefetch(srow1 + x + 2 * srcStride);\n\n uint8x16x3_t v_src10 = vld3q_u8(srow0 + (x * 3));\n uint8x16x3_t v_src20 = vld3q_u8(srow1 + (x * 3));\n\n uint8x16x3_t v_src11 = vld3q_u8(srow0 + (y * 3));\n uint8x16x3_t v_src21 = vld3q_u8(srow1 + (y * 3));\n\n uint8x16x3_t v_dst;\n\n v_dst.val[0] = vcombine_u8(resizeLinearStep(v_src10.val[0], v_src20.val[0], vlutl, vluth, vrw, vcw0, vcw1),\n resizeLinearStep(v_src11.val[0], v_src21.val[0], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n v_dst.val[1] = vcombine_u8(resizeLinearStep(v_src10.val[1], v_src20.val[1], vlutl, vluth, vrw, vcw0, vcw1),\n resizeLinearStep(v_src11.val[1], v_src21.val[1], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n v_dst.val[2] = vcombine_u8(resizeLinearStep(v_src10.val[2], v_src20.val[2], vlutl, vluth, vrw, vcw0, vcw1),\n resizeLinearStep(v_src11.val[2], v_src21.val[2], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n\n vst3q_u8(drow + (col * 3), v_dst);\n }\n }\n else if (channels == 4)\n {\n for (size_t row = 0; row < dsize.height; ++row)\n {\n float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n internal::prefetch(srow0 + x + 2 * srcStride);\n internal::prefetch(srow1 + x + 2 * srcStride);\n\n uint8x16x4_t v_src10 = vld4q_u8(srow0 + (x << 2));\n uint8x16x4_t v_src20 = vld4q_u8(srow1 + (x << 2));\n\n uint8x16x4_t v_src11 = vld4q_u8(srow0 + (y << 2));\n uint8x16x4_t v_src21 = vld4q_u8(srow1 + (y << 2));\n\n uint8x16x4_t v_dst;\n\n v_dst.val[0] = vcombine_u8(resizeLinearStep(v_src10.val[0], v_src20.val[0], vlutl, vluth, vrw, vcw0, vcw1),\n resizeLinearStep(v_src11.val[0], v_src21.val[0], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n v_dst.val[1] = vcombine_u8(resizeLinearStep(v_src10.val[1], v_src20.val[1], vlutl, vluth, vrw, vcw0, vcw1),\n resizeLinearStep(v_src11.val[1], v_src21.val[1], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n v_dst.val[2] = vcombine_u8(resizeLinearStep(v_src10.val[2], v_src20.val[2], vlutl, vluth, vrw, vcw0, vcw1),\n resizeLinearStep(v_src11.val[2], v_src21.val[2], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n v_dst.val[3] = vcombine_u8(resizeLinearStep(v_src10.val[3], v_src20.val[3], vlutl, vluth, vrw, vcw0, vcw1),\n resizeLinearStep(v_src11.val[3], v_src21.val[3], vlutl_, vluth_, vrw, vcw0_, vcw1_));\n\n vst4q_u8(drow + (col << 2), v_dst);\n }\n }\n }\n\n for ( ; col + 8 <= dsize.width; col += 8)\n {\ndownsample_bilinear_8uc1_col_loop8:\n ptrdiff_t col1[8], col2[8];\n f32 cwi[8];\n\n for (s32 k = 0; k < 8; ++k)\n {\n f32 c = (col + k) * scale_x + scale_x_offset;\n col1[k] = floorf(c);\n col2[k] = col1[k] + 1;\n\n cwi[k] = col2[k] - c;\n\n if (col1[k] < 0)\n col1[k] = 0;\n if (col2[k] >= (ptrdiff_t)ssize.width)\n col2[k] = ssize.width - 1;\n }\n\n ptrdiff_t x = std::min(col1[0], ssize.width - 16);\n u8 lutl[8], luth[8];\n for (s32 k = 0; k < 8; ++k)\n {\n lutl[k] = (u8)(col1[k] - x);\n luth[k] = (u8)(col2[k] - x);\n }\n\n uint8x8_t vlutl = vld1_u8(lutl);\n uint8x8_t vluth = vld1_u8(luth);\n float32x4_t vcw0 = vld1q_f32(cwi);\n float32x4_t vcw1 = vld1q_f32(cwi + 4);\n\n if (channels == 1)\n {\n for (size_t row = 0; row < dsize.height; ++row)\n {\n float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n internal::prefetch(srow0 + x + 2 * srcStride);\n internal::prefetch(srow1 + x + 2 * srcStride);\n\n uint8x8_t vres = resizeLinearStep(vld1q_u8(srow0 + x), vld1q_u8(srow1 + x),\n vlutl, vluth,\n vrw, vcw0, vcw1);\n vst1_u8(drow + col, vres);\n }\n }\n else if (channels == 3)\n {\n for (size_t row = 0; row < dsize.height; ++row)\n {\n float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n internal::prefetch(srow0 + x + 2 * srcStride);\n internal::prefetch(srow1 + x + 2 * srcStride);\n\n uint8x16x3_t v_src1 = vld3q_u8(srow0 + (x * 3));\n uint8x16x3_t v_src2 = vld3q_u8(srow1 + (x * 3));\n\n uint8x8x3_t v_dst;\n\n v_dst.val[0] = resizeLinearStep(v_src1.val[0], v_src2.val[0], vlutl, vluth, vrw, vcw0, vcw1);\n v_dst.val[1] = resizeLinearStep(v_src1.val[1], v_src2.val[1], vlutl, vluth, vrw, vcw0, vcw1);\n v_dst.val[2] = resizeLinearStep(v_src1.val[2], v_src2.val[2], vlutl, vluth, vrw, vcw0, vcw1);\n\n vst3_u8(drow + (col * 3), v_dst);\n }\n }\n else if (channels == 4)\n {\n for (size_t row = 0; row < dsize.height; ++row)\n {\n float32x4_t vrw = vdupq_n_f32(coeff[row]);\n\n const u8 * srow0 = internal::getRowPtr(srcBase, srcStride, buf[0 * dsize.height + row]);\n const u8 * srow1 = internal::getRowPtr(srcBase, srcStride, buf[1 * dsize.height + row]);\n u8 * drow = internal::getRowPtr(dstBase, dstStride, row);\n\n internal::prefetch(srow0 + x + 2 * srcStride);\n internal::prefetch(srow1 + x + 2 * srcStride);\n\n uint8x16x4_t v_src1 = vld4q_u8(srow0 + (x << 2));\n uint8x16x4_t v_src2 = vld4q_u8(srow1 + (x << 2));\n\n uint8x8x4_t v_dst;\n\n v_dst.val[0] = resizeLinearStep(v_src1.val[0], v_src2.val[0], vlutl, vluth, vrw, vcw0, vcw1);\n v_dst.val[1] = resizeLinearStep(v_src1.val[1], v_src2.val[1], vlutl, vluth, vrw, vcw0, vcw1);\n v_dst.val[2] = resizeLinearStep(v_src1.val[2], v_src2.val[2], vlutl, vluth, vrw, vcw0, vcw1);\n v_dst.val[3] = resizeLinearStep(v_src1.val[3], v_src2.val[3], vlutl, vluth, vrw, vcw0, vcw1);\n\n vst4_u8(drow + (col << 2), v_dst);\n }\n }\n }\n\n if (col < dsize.width)\n {\n col = dsize.width - 8;\n goto downsample_bilinear_8uc1_col_loop8;\n }\n\n#else\n (void)ssize;\n (void)dsize;\n (void)srcBase;\n (void)srcStride;\n (void)dstBase;\n (void)dstStride;\n (void)wr;\n (void)hr;\n (void)channels;\n#endif\n}\n\n} \/\/ namespace CAROTENE_NS\n","avg_line_length":44.8261861314,"max_line_length":146,"alphanum_fraction":0.5156474216} {"size":3846,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/*\n\tS8 - CO2 sensor library\n\tWritten by AirTracker team\n\tJuly 2018\n*\/\n\n\n#include \"s8.h\"\n\n#define pinRX 2\n#define pinTX 3\nconst byte cmd_readCO2[] = {0xFE,0x04,0x00,0x03,0x00,0x01,0xD5,0xC5};\nconst byte cmd_clearHR1[] = {0xFE, 0x06, 0x00, 0x00, 0x00,0x00, 0x9D, 0xC5};\nconst byte cmd_backgnd_cal[] = {0xFE, 0x06, 0x00, 0x01, 0x7C, 0x06, 0x6C, 0xC7};\nconst byte cmd_readACK[] = {0xFE, 0x03, 0x00, 0x00, 0x00, 0x01, 0x90, 0x05};\nbyte s8_response[]={0,0,0,0,0,0,0,0};\n\nSoftwareSerial s8_serial(pinRX,pinTX); \nint bytecmp(byte req[], byte res[], int num)\n{\n int i;\n for(i=0;i0)\n Serial.println(\"Calibration done!\");\n else\n Serial.println(\"Calibration skipped!\");*\/\n}\n\n\nint S8::sendRequest(byte request[], int byte_request)\n{\n while(!s8_serial.available()) \/\/keep sending request until we start to get a response\n {\n s8_serial.write(request,byte_request);\n delay(50);\n }\n return s8_serial.available();\n}\n\nint S8::getResponse(byte response[], int byte_response) \n{ \n int timeout=0; \/\/set a timeout counter\n while(s8_serial.available() < byte_response ) \/\/Wait to get number of byte response\n {\n timeout++;\n if(timeout > 10) \/\/if it takes to long there was probably an error\n {\n while(s8_serial.available()) \/\/flush whatever we have\n s8_serial.read();\n return 0; \/\/exit and try again\n }\n delay(50);\n }\n int i;\n for (i=0; i < byte_response; i++)\n {\n response[i] = s8_serial.read();\n }\n return i;\n}\nunsigned int S8::getValue(byte packet[])\n{\n int high = packet[3]; \/\/high byte for value is 4th byte in packet in the packet\n int low = packet[4]; \/\/low byte for value is 5th byte in the packet\n unsigned long val = high*256 + low; \/\/Combine high byte and low byte with this formula to get value\n return val* valMultiplier;\n}\n\nunsigned int S8::readCO2()\n{\n int timeout=0; \/\/set a timeout counter\n s8_serial.listen();\n while(!s8_serial.available()) \/\/keep sending request until we start to get a response\n {\n s8_serial.write(cmd_readCO2,8);\n delay(100);\n if(timeout++>10) return 0;\n }\n timeout = 0;\n while(s8_serial.available() < 7 ) \/\/Wait to get a 7 byte response\n {\n timeout++;\n if(timeout > 10) \/\/if it takes to long there was probably an error\n {\n while(s8_serial.available()) \/\/flush whatever we have\n s8_serial.read();\n break; \/\/exit and try again\n }\n delay(50);\n }\n for (int i=0; i < 7; i++)\n {\n s8_response[i] = s8_serial.read();\n }\n int high = s8_response[3]; \/\/high byte for value is 4th byte in packet in the packet\n int low = s8_response[4]; \/\/low byte for value is 5th byte in the packet\n unsigned int val = high*256 + low; \/\/Combine high byte and low byte with this formula to get value\n return val* valMultiplier;\n}\n\n\nint S8::background_calibrate()\n{\n\t\/\/ Step 1\n\tint n;\n\tint r = sendRequest(cmd_clearHR1, 8);\n\tSerial.println(r);\n\tif(r)\n\t{\n\t\tn = getResponse(s8_response,8);\n Serial.println(n);\n \n\t\tif(n==8)\n\t\t{\n\t\t\tif(bytecmp(cmd_clearHR1,s8_response,n)!=0)\n\t\t\t\treturn 0; \/\/ failed\n\t\t} else \n\t\t\t return 0; \/\/ failed\n\t} else \n\t return 0;\n Serial.println(\"OK\");\n \/\/ Step 2 \n\tr = sendRequest(cmd_backgnd_cal, 8);\n\tif(r)\n\t{\n\t\tn = getResponse(s8_response,8);\n\t\tif(n==8)\n\t\t{\n\t\t\tif(bytecmp(cmd_backgnd_cal,s8_response,n)!=0)\n\t\t\t\treturn 0; \/\/ failed\n\t\t} else \n\t\t\treturn 0; \/\/ failed\n\t} else \n\t return 0;\n\t\n\t\/\/ Step 3\n\tdelay(3000);\n\t\n\t\/\/ Step 4\n\tr = sendRequest(cmd_readACK, 8);\n\tif(r)\n\t{\n\t\tn = getResponse(s8_response,7);\n\t\tif(n==7)\n\t\t{\n\t\t\tSerial.println(n);\n\t\t\tint t = s8_response[4] & 0x20;\n Serial.println(t);\n return t; \n\t\t} else \n\t\t\t return 0; \/\/ failed\n\t} else \n\t return 0;\n}\r\n","avg_line_length":23.0299401198,"max_line_length":103,"alphanum_fraction":0.6268850754} {"size":15919,"ext":"hpp","lang":"C++","max_stars_count":10.0,"content":"\/\/---------------------------------------------------------------------------\/\/\n\/\/!\n\/\/! \\file MonteCarlo_EventHandler_def.hpp\n\/\/! \\author Alex Robinson\n\/\/! \\brief Event handler class definition.\n\/\/!\n\/\/---------------------------------------------------------------------------\/\/\n\n#ifndef MONTE_CARLO_ESTIMATOR_HANDLER_DEF_HPP\n#define MONTE_CARLO_ESTIMATOR_HANDLER_DEF_HPP\n\n\/\/ Boost Includes\n#include \n#include \n#include \n#include \n\n\/\/ FRENSIE Includes\n#include \"Utility_GlobalMPISession.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace MonteCarlo{\n\n\/\/ Add an estimator to the handler\n\/*! \\details The estimators will be registered with the appropriate \n * dispatchers. It is important to pass a pointer to the class that maintains\n * the event tags associated with the observer (so that automatic dispatcher\n * registration can occur).\n *\/\ntemplate\nvoid EventHandler::addEstimator( const std::shared_ptr& estimator )\n{\n \/\/ Make sure the observer is valid\n testPrecondition( estimator.get() );\n\n ParticleHistoryObservers::iterator observer_it =\n std::find( d_particle_history_observers.begin(),\n d_particle_history_observers.end(),\n estimator );\n \n if( observer_it == d_particle_history_observers.end() )\n {\n \/\/ Make sure that the particle types have been set\n TEST_FOR_EXCEPTION( estimator->getParticleTypes().empty(),\n std::runtime_error,\n \"The estimator particle type(s) must be set before \"\n \"adding them to the event handler!\" );\n \n EstimatorRegistrationHelper::registerEstimator( *this, estimator );\n\n \/\/ Add the estimator to the map\n d_estimators[estimator->getId()] = estimator;\n \n \/\/ Add the observer to the set\n d_particle_history_observers.push_back( estimator );\n }\n}\n\n\/\/ Struct for registering estimator\ntemplate\nvoid EventHandler::EstimatorRegistrationHelper::registerEstimator(\n EventHandler& event_handler,\n const std::shared_ptr& estimator )\n{\n std::set entity_ids;\n estimator->getEntityIds( entity_ids );\n \n if( estimator->isCellEstimator() )\n {\n event_handler.verifyValidEstimatorCellIds( estimator->getId(),\n entity_ids );\n }\n else\n {\n event_handler.verifyValidEstimatorSurfaceIds( estimator->getId(),\n entity_ids );\n }\n\n std::set particle_types = estimator->getParticleTypes();\n\n event_handler.registerObserver( estimator, entity_ids, particle_types );\n}\n\ntemplate\nvoid EventHandler::EstimatorRegistrationHelper >::registerEstimator(\n EventHandler& event_handler,\n const std::shared_ptr >& estimator )\n{\n std::set particle_types = estimator->getParticleTypes();\n \n event_handler.registerGlobalObserver( estimator, particle_types );\n}\n\n\/\/ Register an observer with the appropriate dispatcher\ntemplate\nvoid EventHandler::registerObserver( const std::shared_ptr& observer,\n const std::set& entity_ids )\n{\n typedef typename boost::mpl::begin::type\n BeginEventTagIterator;\n typedef typename boost::mpl::end::type\n EndEventTagIterator;\n\n ObserverRegistrationHelper::registerObserverWithTag(\n *this,\n\t\t\t\t\t\t\t\t observer,\n\t\t\t\t\t\t\t\t entity_ids );\n}\n\n\/\/ Register an observer with the appropriate dispatcher\ntemplate\nvoid EventHandler::registerObserver( const std::shared_ptr& observer,\n const std::set& entity_ids,\n const std::set& particle_types )\n{\n typedef typename boost::mpl::begin::type\n BeginEventTagIterator;\n typedef typename boost::mpl::end::type\n EndEventTagIterator;\n\n ObserverRegistrationHelper::registerObserverWithTag(\n *this,\n observer,\n entity_ids,\n particle_types );\n}\n\n\/\/ Register a global observer with the appropriate dispatcher\ntemplate\nvoid EventHandler::registerGlobalObserver(\n const std::shared_ptr& observer )\n{\n typedef typename boost::mpl::begin::type\n BeginEventTagIterator;\n typedef typename boost::mpl::end::type\n EndEventTagIterator;\n\n ObserverRegistrationHelper::registerGlobalObserverWithTag(\n *this,\n\t\t\t\t\t\t\t\t observer );\n}\n\n\/\/ Register a global observer with the appropriate dispatcher\ntemplate\nvoid EventHandler::registerGlobalObserver(\n const std::shared_ptr& observer,\n const std::set& particle_types )\n{\n typedef typename boost::mpl::begin::type\n BeginEventTagIterator;\n typedef typename boost::mpl::end::type\n EndEventTagIterator;\n\n ObserverRegistrationHelper::registerGlobalObserverWithTag(\n *this,\n observer,\n particle_types );\n}\n\n\/\/ Register the obs. with dispatchers associated with BeginEventTag tag\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerObserverWithTag(\n EventHandler& event_handler,\n const std::shared_ptr& observer,\n const std::set& entity_ids )\n{\n event_handler.registerObserverWithTag(\n observer,\n entity_ids,\n typename boost::mpl::deref::type() );\n\n ObserverRegistrationHelper::type,EndEventTagIterator>::registerObserverWithTag(\n event_handler,\n observer,\n entity_ids );\n}\n\n\/\/ End registration iteration\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerObserverWithTag(\n EventHandler& event_handler,\n\t\t\t const std::shared_ptr& observer,\n const std::set& entity_ids )\n{ \/* ... *\/ }\n\n\/\/ Register the obs. with dispatchers associated with BeginEventTag tag\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerObserverWithTag(\n EventHandler& event_handler,\n const std::shared_ptr& observer,\n const std::set& entity_ids,\n const std::set& particle_types )\n{\n event_handler.registerObserverWithTag(\n observer,\n entity_ids,\n particle_types,\n typename boost::mpl::deref::type() );\n\n ObserverRegistrationHelper::type,EndEventTagIterator>::registerObserverWithTag(\n event_handler,\n observer,\n entity_ids,\n particle_types );\n}\n\n\/\/ End registration iteration\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerObserverWithTag(\n EventHandler& event_handler,\n\t\t\t const std::shared_ptr& observer,\n const std::set& entity_ids,\n const std::set& particle_types )\n{ \/* ... *\/ }\n\n\/\/ Register the global observer with the global dispatcher associated with\n\/\/ BeginEventTag tag\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerGlobalObserverWithTag(\n EventHandler& event_handler,\n const std::shared_ptr& observer )\n{\n event_handler.registerGlobalObserverWithTag(\n observer,\n typename boost::mpl::deref::type() );\n\n ObserverRegistrationHelper::type,EndEventTagIterator>::registerGlobalObserverWithTag(\n event_handler,\n observer );\n}\n\n\/\/ End global registration iteration\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerGlobalObserverWithTag(\n EventHandler& event_handler,\n const std::shared_ptr& observer)\n{ \/* ... *\/ }\n\n\/\/ Register the global observer with the global dispatcher associated with\n\/\/ BeginEventTag tag\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerGlobalObserverWithTag(\n EventHandler& event_handler,\n const std::shared_ptr& observer,\n const std::set& particle_types )\n{\n event_handler.registerGlobalObserverWithTag(\n observer,\n particle_types,\n typename boost::mpl::deref::type() );\n\n ObserverRegistrationHelper::type,EndEventTagIterator>::registerGlobalObserverWithTag(\n event_handler,\n observer );\n}\n\n\/\/ End global registration iteration\ntemplate\ntemplate\nvoid EventHandler::ObserverRegistrationHelper::registerGlobalObserverWithTag(\n EventHandler& event_handler,\n const std::shared_ptr& observer,\n const std::set& particle_types )\n{ \/* ... *\/ }\n\n\/\/ Save the data to an archive\ntemplate\nvoid EventHandler::save( Archive& ar, const unsigned version ) const\n{\n \/\/ Save the base class data\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleCollidingInCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleCrossingSurfaceEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleEnteringCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleLeavingCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleSubtrackEndingInCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleSubtrackEndingGlobalEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleGoneGlobalEventHandler );\n\n \/\/ Save the local data (ignore the model, snapshot counters)\n ar & BOOST_SERIALIZATION_NVP( d_simulation_completion_criterion );\n\n uint64_t number_of_committed_histories =\n this->getNumberOfCommittedHistories();\n \n ar & BOOST_SERIALIZATION_NVP( number_of_committed_histories );\n\n double elapsed_time = this->getElapsedTime();\n \n ar & BOOST_SERIALIZATION_NVP( elapsed_time );\n ar & BOOST_SERIALIZATION_NVP( d_estimators );\n ar & BOOST_SERIALIZATION_NVP( d_particle_trackers );\n ar & BOOST_SERIALIZATION_NVP( d_particle_history_observers );\n}\n\n\/\/ Load the data to an archive\ntemplate\nvoid EventHandler::load( Archive& ar, const unsigned version )\n{\n \/\/ Load the base class data\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleCollidingInCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleCrossingSurfaceEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleEnteringCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleLeavingCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleSubtrackEndingInCellEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleSubtrackEndingGlobalEventHandler );\n ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( ParticleGoneGlobalEventHandler );\n\n \/\/ Load the local data (ignore the model)\n ar & BOOST_SERIALIZATION_NVP( d_simulation_completion_criterion );\n\n uint64_t number_of_committed_histories;\n \n ar & BOOST_SERIALIZATION_NVP( number_of_committed_histories );\n\n d_number_of_committed_histories.resize( 1 );\n d_number_of_committed_histories.front() = number_of_committed_histories;\n\n if( number_of_committed_histories > 0 )\n ParticleHistoryObserver::setNumberOfHistories( number_of_committed_histories );\n\n d_number_of_committed_histories_from_last_snapshot.resize( 1 );\n d_number_of_committed_histories_from_last_snapshot[0] = 0;\n\n ar & boost::serialization::make_nvp( \"elapsed_time\", d_elapsed_simulation_time ); \n\n if( d_elapsed_simulation_time > 0.0 )\n ParticleHistoryObserver::setElapsedTime( d_elapsed_simulation_time );\n\n d_number_of_committed_histories_from_last_snapshot.resize( 1, 0 );\n\n d_simulation_timer = Utility::GlobalMPISession::createTimer();\n d_snapshot_timer = Utility::GlobalMPISession::createTimer();\n \n ar & BOOST_SERIALIZATION_NVP( d_estimators );\n ar & BOOST_SERIALIZATION_NVP( d_particle_trackers );\n ar & BOOST_SERIALIZATION_NVP( d_particle_history_observers );\n}\n\n} \/\/ end MonteCarlo namespace\n\nEXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, EventHandler );\n\n#endif \/\/ end MONTE_CARLO_EVENT_HANDLER_DEF_HPP\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end MonteCarlo_EventHandler_def.hpp\n\/\/---------------------------------------------------------------------------\/\/\n","avg_line_length":44.8422535211,"max_line_length":136,"alphanum_fraction":0.6529932785} {"size":1818,"ext":"hpp","lang":"C++","max_stars_count":2.0,"content":"\/*\n * fold_pairs.hpp\n *\n * Created on: Aug 28, 2009\n * Author: stewie\n *\/\n\n#ifndef FOLD_PAIRS_HPP_\n#define FOLD_PAIRS_HPP_\n\n#include \n\n#include \n#include \n#include \n\nnamespace bn {\n\nnamespace util {\n\n\/**\n * Applies binary functions @a s and @a p on all the 2-combinations without\n * repetition<\/em> of elements in the given ranges.\n *\n * See fold_cartesian_product() for a formal description of the algorithm\n * replacing the cartesian product with the sequence of 2-combinations.\n * @param first forward iterator to the initial position of the range\n * @param last forward iterator to the final position of the range\n * @param init initial value for the accumulator\n * @param s binary function that implements the sum\n * @param p binary function that implements the product\n * @return the accumulated value\n *\n * @see for_each_pair() for the iteration version.\n *\/\ntemplate T fold_pairs(\n\t\tForwardIterator first, ForwardIterator last, T init, Sum s = std::plus<\n\t\t\t\tT>(), Product p = std::multiplies()) {\n\tfor (; first != last; ++first)\n\t\tfor (ForwardIterator it = boost::next(first); it != last; ++it)\n\t\t\tinit = s(init, p(*first, *it));\n\treturn init;\n}\n\ntemplate T fold_pairs(\n\t\tForwardRange& r, T init, Sum s = std::plus(), Product p =\n\t\t\t\tstd::multiplies()) {\n\treturn fold_pairs(boost::begin(r), boost::end(r), init, s, p);\n}\n\ntemplate T fold_pairs(\n\t\tconst ForwardRange& r, T init, Sum s = std::plus(), Product p =\n\t\t\t\tstd::multiplies()) {\n\treturn fold_pairs(boost::begin(r), boost::end(r), init, s, p);\n}\n\n}\n\n}\n\n#endif \/* FOLD_PAIRS_HPP_ *\/\n","avg_line_length":29.3225806452,"max_line_length":80,"alphanum_fraction":0.699669967} {"size":4032,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"\ufeff\/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace Aws::LexModelBuildingService::Model;\nusing namespace Aws::Utils::Json;\nusing namespace Aws::Utils;\nusing namespace Aws;\n\nPutIntentResult::PutIntentResult() : \n m_createVersion(false)\n{\n}\n\nPutIntentResult::PutIntentResult(const Aws::AmazonWebServiceResult& result) : \n m_createVersion(false)\n{\n *this = result;\n}\n\nPutIntentResult& PutIntentResult::operator =(const Aws::AmazonWebServiceResult& result)\n{\n JsonView jsonValue = result.GetPayload().View();\n if(jsonValue.ValueExists(\"name\"))\n {\n m_name = jsonValue.GetString(\"name\");\n\n }\n\n if(jsonValue.ValueExists(\"description\"))\n {\n m_description = jsonValue.GetString(\"description\");\n\n }\n\n if(jsonValue.ValueExists(\"slots\"))\n {\n Array slotsJsonList = jsonValue.GetArray(\"slots\");\n for(unsigned slotsIndex = 0; slotsIndex < slotsJsonList.GetLength(); ++slotsIndex)\n {\n m_slots.push_back(slotsJsonList[slotsIndex].AsObject());\n }\n }\n\n if(jsonValue.ValueExists(\"sampleUtterances\"))\n {\n Array sampleUtterancesJsonList = jsonValue.GetArray(\"sampleUtterances\");\n for(unsigned sampleUtterancesIndex = 0; sampleUtterancesIndex < sampleUtterancesJsonList.GetLength(); ++sampleUtterancesIndex)\n {\n m_sampleUtterances.push_back(sampleUtterancesJsonList[sampleUtterancesIndex].AsString());\n }\n }\n\n if(jsonValue.ValueExists(\"confirmationPrompt\"))\n {\n m_confirmationPrompt = jsonValue.GetObject(\"confirmationPrompt\");\n\n }\n\n if(jsonValue.ValueExists(\"rejectionStatement\"))\n {\n m_rejectionStatement = jsonValue.GetObject(\"rejectionStatement\");\n\n }\n\n if(jsonValue.ValueExists(\"followUpPrompt\"))\n {\n m_followUpPrompt = jsonValue.GetObject(\"followUpPrompt\");\n\n }\n\n if(jsonValue.ValueExists(\"conclusionStatement\"))\n {\n m_conclusionStatement = jsonValue.GetObject(\"conclusionStatement\");\n\n }\n\n if(jsonValue.ValueExists(\"dialogCodeHook\"))\n {\n m_dialogCodeHook = jsonValue.GetObject(\"dialogCodeHook\");\n\n }\n\n if(jsonValue.ValueExists(\"fulfillmentActivity\"))\n {\n m_fulfillmentActivity = jsonValue.GetObject(\"fulfillmentActivity\");\n\n }\n\n if(jsonValue.ValueExists(\"parentIntentSignature\"))\n {\n m_parentIntentSignature = jsonValue.GetString(\"parentIntentSignature\");\n\n }\n\n if(jsonValue.ValueExists(\"lastUpdatedDate\"))\n {\n m_lastUpdatedDate = jsonValue.GetDouble(\"lastUpdatedDate\");\n\n }\n\n if(jsonValue.ValueExists(\"createdDate\"))\n {\n m_createdDate = jsonValue.GetDouble(\"createdDate\");\n\n }\n\n if(jsonValue.ValueExists(\"version\"))\n {\n m_version = jsonValue.GetString(\"version\");\n\n }\n\n if(jsonValue.ValueExists(\"checksum\"))\n {\n m_checksum = jsonValue.GetString(\"checksum\");\n\n }\n\n if(jsonValue.ValueExists(\"createVersion\"))\n {\n m_createVersion = jsonValue.GetBool(\"createVersion\");\n\n }\n\n if(jsonValue.ValueExists(\"kendraConfiguration\"))\n {\n m_kendraConfiguration = jsonValue.GetObject(\"kendraConfiguration\");\n\n }\n\n if(jsonValue.ValueExists(\"inputContexts\"))\n {\n Array inputContextsJsonList = jsonValue.GetArray(\"inputContexts\");\n for(unsigned inputContextsIndex = 0; inputContextsIndex < inputContextsJsonList.GetLength(); ++inputContextsIndex)\n {\n m_inputContexts.push_back(inputContextsJsonList[inputContextsIndex].AsObject());\n }\n }\n\n if(jsonValue.ValueExists(\"outputContexts\"))\n {\n Array outputContextsJsonList = jsonValue.GetArray(\"outputContexts\");\n for(unsigned outputContextsIndex = 0; outputContextsIndex < outputContextsJsonList.GetLength(); ++outputContextsIndex)\n {\n m_outputContexts.push_back(outputContextsJsonList[outputContextsIndex].AsObject());\n }\n }\n\n\n\n return *this;\n}\n","avg_line_length":24.736196319,"max_line_length":130,"alphanum_fraction":0.7338789683} {"size":99411,"ext":"cpp","lang":"C++","max_stars_count":18.0,"content":"\/*===========================================================================\r\n *\r\n * File:\t\tSrrecorddialog.CPP\r\n * Author:\t\tDave Humphrey (dave@uesp.net)\r\n * Created On:\t26 November 2011\r\n *\r\n * Description\r\n *\r\n *=========================================================================*\/\r\n\r\n\t\/* Include Files *\/\r\n#include \"stdafx.h\"\r\n#include \"srrecorddialog.h\"\r\n#include \"sreditdlghandler.h\"\r\n#include \"resource.h\"\r\n#include \"sredit.h\"\r\n#include \"sreditdoc.h\"\r\n\/\/#include \"srbipedpartsdlg.h\"\r\n\/\/#include \"srbipedpartslistdlg.h\"\r\n#include \"mainfrm.h\"\r\n#include \"SrConditionDlg.h\"\r\n#include \"SrBoundsDlg.h\"\r\n#include \"SrScriptPropertyDlg.h\"\r\n#include \"SrSelectScriptDlg.h\"\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Begin Local Definitions\r\n *\r\n *=========================================================================*\/\r\n\tIMPLEMENT_DYNCREATE(CSrRecordDialog, CFormView);\r\n\/*===========================================================================\r\n *\t\tEnd of Local Definitions\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Begin Message Map\r\n *\r\n *=========================================================================*\/\r\nBEGIN_MESSAGE_MAP(CSrRecordDialog, CFormView)\r\n\tON_WM_CONTEXTMENU()\r\n\tON_WM_INITMENUPOPUP()\r\n\tON_WM_DESTROY()\r\n\tON_COMMAND(ID_APPLY_BUTTON, OnApply)\r\n\tON_COMMAND(ID_CANCEL_BUTTON, OnCancel)\r\n\tON_COMMAND(ID_SAVE_BUTTON, OnSave)\r\n\tON_EN_KILLFOCUS(IDC_EDITORID, OnKillfocusEditorid)\r\n\tON_BN_CLICKED(IDC_EDIT_ENCHANTMENT, OnEditEnchantment)\r\n\tON_BN_CLICKED(IDC_SELECTENCHANT_BUTTON, OnSelectEnchantment)\r\n\tON_MESSAGE(ID_SRRECORDLIST_ACTIVATE, OnEditRecordMsg)\r\n\tON_NOTIFY(ID_SRRECORDLIST_CHECKDROP, IDC_ENCHANTMENT, OnDropEnchant)\r\n\tON_NOTIFY(ID_SRRECORDLIST_DROP, IDC_ENCHANTMENT, OnDropEnchant)\r\n\tON_COMMAND(ID_EDIT_CUT, OnEditCut)\r\n\tON_COMMAND(ID_EDIT_COPY, OnEditCopy)\r\n\tON_COMMAND(ID_EDIT_PASTE, OnEditPaste)\r\n\tON_COMMAND(ID_EDIT_SELECTALL, OnEditSelectAll)\r\n\tON_COMMAND(ID_EDIT_UNDO, OnEditUndo)\r\n\tON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCopy)\r\n\tON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditCopy)\r\n\tON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy)\r\n\tON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateEditPaste)\r\n\tON_UPDATE_COMMAND_UI(ID_EDIT_SELECTALL, OnUpdateEditSelectAll)\r\n\tON_WM_HELPINFO()\r\n\tON_COMMAND(ID_HELP, OnHelp)\r\n\tON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_MODEL, OnDropModel)\r\n\tON_NOTIFY(ID_SRRESOURCE_DROP, IDC_MODEL, OnDropModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_INVENTORYICON, OnDropIcon)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_INVENTORYICON, OnDropIcon)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_SOUNDFILE, OnDropSoundFile)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_SOUNDFILE, OnDropSoundFile)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_MALEICON, OnDropMaleIcon)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_MALEICON, OnDropMaleIcon)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_FEMALEICON, OnDropFemaleIcon)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_FEMALEICON, OnDropFemaleIcon)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_MALEWORLD, OnDropMaleWorldModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_MALEWORLD, OnDropMaleWorldModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_MALEBIPED, OnDropMaleBipedModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_MALEBIPED, OnDropMaleBipedModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_FEMALEWORLD, OnDropFemaleWorldModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_FEMALEWORLD, OnDropFemaleWorldModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_FEMALEBIPED, OnDropFemaleBipedModel)\r\n\t\/\/ON_NOTIFY(ID_SRRESOURCE_DROP, IDC_FEMALEBIPED, OnDropFemaleBipedModel)\r\n\tON_COMMAND(IDC_SELECT_MODEL, OnSelectModel)\r\n\t\/\/ON_COMMAND(IDC_SELECT_ICON, OnSelectIcon)\r\n\t\/\/ON_COMMAND(IDC_SELECT_SOUNDFILE, OnSelectSoundFile)\r\n\t\/\/ON_COMMAND(IDC_SELECT_MALEICON, OnSelectMaleIcon)\r\n\t\/\/ON_COMMAND(IDC_SELECT_FEMALEICON, OnSelectFemaleIcon)\r\n\t\/\/ON_COMMAND(IDC_SELECT_MALEWORLDMODEL, OnSelectMaleWorldModel)\r\n\t\/\/ON_COMMAND(IDC_SELECT_MALEBIPEDMODEL, OnSelectMaleBipedModel)\r\n\t\/\/ON_COMMAND(IDC_SELECT_FEMALEWORLDMODEL, OnSelectFemaleWorldModel)\r\n\t\/\/ON_COMMAND(IDC_SELECT_FEMALEBIPEDMODEL, OnSelectFemaleBipedModel)\r\n\t\/\/ON_BN_CLICKED(IDC_SELECTSOUND_BUTTON, OnSelectsoundButton)\r\n\t\/\/ON_BN_CLICKED(IDC_EDIT_SOUND, OnEditSound)\r\n\t\/\/\/\/ON_NOTIFY(ID_SRRECORDLIST_CHECKDROP, IDC_SOUND, OnDropSound)\r\n\t\/\/ON_NOTIFY(ID_SRRECORDLIST_DROP, IDC_SOUND, OnDropSound)\r\n\tON_BN_CLICKED(IDC_ADDKEYWORD_BUTTON, OnBnClickedAddkeywordButton)\r\n\tON_BN_CLICKED(IDC_EDITKEYWORD_BUTTON, OnBnClickedEditkeywordButton)\r\n\tON_BN_CLICKED(IDC_DELKEYWORD_BUTTON, OnBnClickedDelkeywordButton)\r\n\tON_LBN_DBLCLK(IDC_KEYWORDS, OnBnClickedEditkeywordButton)\r\n\tON_LBN_SELCHANGE(IDC_KEYWORDS, OnLbnSelchangeKeywords)\r\n\tON_COMMAND(ID_EDIT_FIND, &CSrRecordDialog::OnEditFind)\r\n\tON_BN_CLICKED(IDC_CONDITION_BUTTON, &CSrRecordDialog::OnBnClickedConditionButton)\r\n\tON_BN_CLICKED(IDC_SELECTDROPSOUND_BUTTON, &CSrRecordDialog::OnBnClickedSelectdropsoundButton)\r\n\tON_BN_CLICKED(IDC_SELECTPICKUP_BUTTON, &CSrRecordDialog::OnBnClickedSelectpickupButton)\r\n\tON_BN_CLICKED(IDC_SELECTPICKUPSOUND_BUTTON, &CSrRecordDialog::OnBnClickedSelectpickupButton)\r\n\tON_NOTIFY(ID_SRRECORDLIST_CHECKDROP, IDC_DROPSOUND, OnDropDropSound)\r\n\tON_NOTIFY(ID_SRRECORDLIST_DROP, IDC_DROPSOUND, OnDropDropSound)\r\n\tON_NOTIFY(ID_SRRECORDLIST_CHECKDROP, IDC_PICKUPSOUND, OnDropPickupSound)\r\n\tON_NOTIFY(ID_SRRECORDLIST_DROP, IDC_PICKUPSOUND, OnDropPickupSound)\r\n\tON_NOTIFY(ID_SRRECORDLIST_CHECKDROP, IDC_KEYWORDS, OnDropKeywords)\r\n\tON_NOTIFY(ID_SRRECORDLIST_DROP, IDC_KEYWORDS, OnDropKeywords)\r\n\tON_BN_CLICKED(IDC_EDIT_DROPSOUND, &CSrRecordDialog::OnBnClickedEditDropsound)\r\n\tON_BN_CLICKED(IDC_EDIT_PICKUPSOUND, &CSrRecordDialog::OnBnClickedEditPickupsound)\r\n\tON_BN_CLICKED(IDC_BOUNDS, OnBnClickedBounds)\r\n\r\n\tON_BN_CLICKED(IDC_ADDSCRIPT, &CSrArmoView::OnBnClickedAddscript)\r\n\tON_BN_CLICKED(IDC_EDITPROPERTIESSCRIPT, &CSrArmoView::OnBnClickedEditpropertiesscript)\r\n\tON_BN_CLICKED(IDC_EDITSCRIPT, &CSrArmoView::OnBnClickedEditscript)\r\n\tON_BN_CLICKED(IDC_DELSCRIPT, &CSrArmoView::OnBnClickedDelscript)\r\n\tON_LBN_DBLCLK(IDC_SCRIPT_LIST, &CSrRecordDialog::OnLbnDblclkScripts)\r\n\tON_COMMAND(ID_SCRIPTRECORD_ADD, &CSrRecordDialog::OnScriptrecordAdd)\r\n\tON_COMMAND(ID_SCRIPTRECORD_ADDNEW, &CSrRecordDialog::OnScriptrecordAddNew)\r\n\tON_COMMAND(ID_SCRIPTRECORD_EDITPROPERTIES, &CSrRecordDialog::OnScriptrecordEditProperties)\r\n\tON_COMMAND(ID_SCRIPTRECORD_EDITSCRIPT, &CSrRecordDialog::OnScriptrecordEditScript)\r\n\tON_COMMAND(ID_SCRIPTRECORD_DELETE, &CSrRecordDialog::OnScriptrecordDelete)\r\n\tON_UPDATE_COMMAND_UI(ID_SCRIPTRECORD_EDITPROPERTIES, &CSrRecordDialog::OnUpdateScriptrecordExists)\r\n\tON_UPDATE_COMMAND_UI(ID_SCRIPTRECORD_EDITSCRIPT, &CSrRecordDialog::OnUpdateScriptrecordExists)\r\n\tON_UPDATE_COMMAND_UI(ID_SCRIPTRECORD_DELETE, &CSrRecordDialog::OnUpdateScriptrecordExists)\r\n\tON_NOTIFY(ID_SRRESOURCE_CHECKDROP, IDC_SCRIPT_LIST, OnDropScript)\r\n\tON_NOTIFY(ID_SRRESOURCE_DROP, IDC_SCRIPT_LIST, OnDropScript)\r\n\tON_COMMAND(ID_SCRIPTRECORD_COPYSCRIPTS, &CSrRecordDialog::OnScriptrecordCopyscripts)\r\n\tON_COMMAND(ID_SCRIPTRECORD_PASTESCRIPTS, &CSrRecordDialog::OnScriptrecordPastescripts)\r\n\tON_UPDATE_COMMAND_UI(ID_SCRIPTRECORD_COPYSCRIPTS, &CSrRecordDialog::OnUpdateScriptrecordCopyscripts)\r\n\tON_UPDATE_COMMAND_UI(ID_SCRIPTRECORD_PASTESCRIPTS, &CSrRecordDialog::OnUpdateScriptrecordPastescripts)\r\n\r\n\tON_COMMAND(ID_CONDITIONRECORD_COPY, &CSrRecordDialog::OnConditionrecordCopy)\r\n\tON_COMMAND(ID_CONDITIONRECORD_PASTE, &CSrRecordDialog::OnConditionrecordPaste)\r\n\tON_COMMAND(ID_CONDITIONRECORD_DELETEALL, &CSrRecordDialog::OnConditionrecordDeleteAll)\r\n\tON_UPDATE_COMMAND_UI(ID_CONDITIONRECORD_COPY, &CSrRecordDialog::OnUpdateConditionrecordCopy)\r\n\tON_UPDATE_COMMAND_UI(ID_CONDITIONRECORD_PASTE, &CSrRecordDialog::OnUpdateConditionrecordPaste)\r\n\tON_UPDATE_COMMAND_UI(ID_CONDITIONRECORD_DELETEALL, &CSrRecordDialog::OnUpdateConditionrecordDeleteAll)\r\n\r\n\tON_COMMAND(ID_KEYWORD_ADD, &CSrRecordDialog::OnKeywordAdd)\r\n\tON_COMMAND(ID_KEYWORD_EDIT, &CSrRecordDialog::OnKeywordEdit)\r\n\tON_COMMAND(ID_KEYWORD_EDITBASE, &CSrRecordDialog::OnKeywordEditBase)\r\n\tON_COMMAND(ID_KEYWORD_DELETE, &CSrRecordDialog::OnKeywordDelete)\r\n\tON_UPDATE_COMMAND_UI(ID_KEYWORD_EDIT, &CSrRecordDialog::OnUpdateKeywordEdit)\r\n\tON_UPDATE_COMMAND_UI(ID_KEYWORD_EDITBASE, &CSrRecordDialog::OnUpdateKeywordEdit)\r\n\tON_UPDATE_COMMAND_UI(ID_KEYWORD_DELETE, &CSrRecordDialog::OnUpdateKeywordEdit)\r\n\tEND_MESSAGE_MAP()\r\n\/*===========================================================================\r\n *\t\tEnd of Message Map\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Begin Default UI Fields\r\n *\r\n *=========================================================================*\/\r\nBEGIN_SRRECUIFIELDS(CSrRecordDialog)\r\nEND_SRRECUIFIELDS()\r\n\/*===========================================================================\r\n *\t\tEnd of Default UI Fields\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Begin Tooltip Definitions\r\n *\r\n *=========================================================================*\/\r\nstruct obrdtooltip_t {\r\n\tint ControlID;\r\n\tint StringID;\r\n};\r\n\r\nstatic obrdtooltip_t s_ToolTipInfo[] = {\r\n\t{ ID_SAVE_BUTTON,\t\t\t\tIDS_TT_SAVE },\r\n\t{ ID_APPLY_BUTTON,\t\t\t\tIDS_TT_APPLY },\r\n\t{ ID_CANCEL_BUTTON,\t\t\t\tIDS_TT_CANCEL },\r\n\t{ IDC_KEYWORDS,\t\t\t\t\tIDS_TT_KEYWORDS },\r\n\t{ IDC_ADDKEYWORD_BUTTON,\t\tIDS_TT_KEYWORDS },\r\n\t{ IDC_EDITKEYWORD_BUTTON,\t\tIDS_TT_KEYWORDS },\r\n\t{ IDC_DELKEYWORD_BUTTON,\t\tIDS_TT_KEYWORDS },\r\n\t\/\/{ IDC_BIPEDPARTS_BUTTON,\t\tIDS_TT_EDITBIPED },\r\n\t\/\/{ IDC_EDIT_SCRIPT,\t\t\t\tIDS_TT_EDITSCRIPT },\r\n\t\/\/{ IDC_SELECTSCRIPT_BUTTON,\t\tIDS_TT_SELECTSCRIPT },\r\n\t{ IDC_EDIT_ENCHANTMENT,\t\t\tIDS_TT_EDITENCHANT },\r\n\t\/\/{ IDC_SELECTENCHANT_BUTTON,\t\tIDS_TT_SELECTENCHANT },\r\n\t\/\/{ IDC_SELECTCREATURE_BUTTON,\tIDS_TT_SELECTCREATURE },\r\n\t\/\/{ IDC_EDIT_CREATURETEMPLATE,\tIDS_TT_EDITCREATURE },\r\n\t\/\/{ IDC_EDIT_SOUND,\t\t\t\tIDS_TT_EDITSOUND },\r\n\t\/\/{ IDC_SELECTSOUND_BUTTON,\t\tIDS_TT_SELECTSOUND },\r\n\t\/\/{ IDC_EDIT_OPENSOUND, IDS_TT_EDITSOUND },\r\n\t\/\/{ IDC_EDIT_CLOSESOUND, IDS_TT_EDITSOUND },\r\n\t\/\/{ IDC_SELECTOPENSOUND_BUTTON, IDS_TT_SELECTSOUND },\r\n\t\/\/{ IDC_SELECTCLOSESOUND_BUTTON, IDS_TT_SELECTSOUND },\r\n\t\/\/{ IDC_EDIT_INGREDIANT,\t\t\tIDS_TT_EDITINGREDIENT },\r\n\t\/\/{ IDC_SELECTINGREDIANT_BUTTON, IDS_TT_SELECTINGREDIENT },\r\n\t\/\/{ IDC_MINATT_SLIDER, IDS_TT_MINATTENUATION },\r\n\t\/\/{ IDC_MAXATT_SLIDER, IDS_TT_MAXATTENUATION },\r\n\t\/\/{ IDC_STATATT_SLIDER, IDS_TT_STATICATTENUATION },\r\n\t\/\/{ IDC_STARTTIME_SLIDER, IDS_TT_STARTTIME },\r\n\t\/\/{ IDC_STOPTIME_SLIDER, IDS_TT_STOPTIME },\r\n\t\/\/{ IDC_COLOR,\t\t\t\t\tIDS_TT_COLORBOX },\r\n\t{ 0, 0 }\r\n};\r\n\/*===========================================================================\r\n *\t\tEnd of Tooltip Definitions\r\n *=========================================================================*\/\r\n\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Constructor\r\n *\r\n *=========================================================================*\/\r\nCSrRecordDialog::CSrRecordDialog (const int ID) : CFormView(ID)\r\n{\r\n m_pRecordHandler = NULL;\r\n m_pDlgHandler = NULL;\r\n m_pEditorIDField = NULL;\r\n m_pBipedPartsField = NULL;\r\n m_pEnchantField = NULL;\r\n m_pSoundField = NULL;\r\n m_pModelField = NULL;\r\n m_pIconField = NULL;\r\n m_pSoundFileField = NULL;\r\n m_pConditionField = NULL;\r\n m_pPickupSoundField = NULL;\r\n m_pDropSoundField = NULL;\r\n m_pBoundsField = NULL;\r\n m_IgnoreConditions = false;\r\n m_pScriptList = NULL;\r\n m_pKeywordsField = NULL;\r\n\r\n m_pMaleWorldModelField = NULL;\r\n m_pMaleBipedModelField = NULL;\r\n m_pFemaleWorldModelField = NULL;\r\n m_pFemaleBipedModelField = NULL;\r\n m_pMaleIconField = NULL;\r\n m_pFemaleIconField = NULL;\r\n\r\n m_pTabControl = NULL;\r\n\r\n m_NoActivateRecord = false;\r\n\r\n m_hAccelerator = NULL;\r\n m_AcceleratorID = IDR_DEFAULT_RECORD_ACCEL;\r\n\r\n m_InitialSetData = true;\r\n\r\n m_EnchantType = 0;\r\n\r\n m_TitlePrefix = _T(\"Unknown\");\r\n\r\n memset(&m_BoundsCopy, 0, sizeof(m_BoundsCopy));\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class CSrRecordDialog Constructor\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void ClearControlData (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::ClearControlData (void) \r\n{\r\n SetTitle(NULL);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::ClearControlData()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void Close (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::Close (void) \r\n{\r\n GetParentFrame()->DestroyWindow();\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::Close()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void DoDataExchange (pDX);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::DoDataExchange(CDataExchange* pDX) \r\n{\r\n CFormView::DoDataExchange(pDX);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::DoDataExchange()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void GetControlData (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::GetControlData (void) {\r\n CSrIdRecord* pIdRecord;\r\n\r\n assert(m_EditInfo.pNewRecord != NULL);\r\n if (GetOutputRecord() == NULL) return;\r\n\r\n\t\/* Update the editor id if required *\/\r\n if (m_EditInfo.HasUpdatedID || m_EditInfo.IsNew) {\r\n pIdRecord = SrCastClass(CSrIdRecord, GetOutputRecord());\r\n if (pIdRecord != NULL) pIdRecord->SetEditorID(m_EditInfo.NewEditorID);\r\n }\r\n\r\n\tUpdateEditorID();\r\n\tGetScriptControlData();\r\n\tSaveScriptData();\r\n\tGetUIFieldData();\r\n\tSaveConditions();\t\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::GetControlData()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void GetUIFieldData (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::GetUIFieldData (void) {\r\n sruirecfields_t*\tpFields;\r\n CButton*\t\t\tpButton;\r\n CString\t\t\tBuffer;\r\n CWnd*\t\t\t\tpWnd;\r\n dword\t\t\t\tIndex;\r\n bool\t\t\t\tResult;\r\n\r\n if (GetOutputRecord() == NULL) return;\r\n\r\n pFields = GetUIFields();\r\n if (pFields == NULL) return;\r\n\r\n for (Index = 0; pFields[Index].FieldID != SR_FIELD_NONE; ++Index) {\r\n if (pFields[Index].FieldID == SR_FIELD_FORMID) continue;\r\n if (pFields[Index].FieldID == SR_FIELD_EDITORID) continue;\r\n\r\n pWnd = GetDlgItem(pFields[Index].ControlID);\r\n\r\n if (pWnd == NULL)\r\n\t{\t\r\n\t\tif (m_pTabControl != NULL) pWnd = m_pTabControl->FindChild(pFields[Index].ControlID);\r\n\t\tif (pWnd == NULL) continue;\r\n\t}\r\n\t\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n pWnd->GetWindowText(Buffer);\r\n\r\n Result = GetOutputRecord()->SetField(pFields[Index].FieldID, Buffer);\r\n if (!Result) continue;\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CComboBox))) {\r\n pWnd->GetWindowText(Buffer);\r\n \r\n Result = GetOutputRecord()->SetField(pFields[Index].FieldID, Buffer);\r\n if (!Result) continue;\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CButton))) {\r\n pButton = (CButton *) pWnd;\r\n\r\n\t if ((pButton->GetButtonStyle() & BS_CHECKBOX) != 0)\r\n\t {\r\n\t\tBuffer = (pButton->GetCheck() != 0) ? \"true\" : \"false\" ;\r\n\t\tResult = GetOutputRecord()->SetField(pFields[Index].FieldID, Buffer);\r\n\t\tif (!Result) continue;\r\n\t }\r\n\t else if (pButton == m_pBoundsField)\r\n\t {\r\n\t\t pButton->GetWindowText(Buffer);\r\n\t\t Result = GetOutputRecord()->SetField(pFields[Index].FieldID, Buffer);\r\n\t\t if (!Result) continue;\r\n\t }\r\n }\r\n\telse if (pWnd->IsKindOf(RUNTIME_CLASS(CListBox)))\r\n\t{\r\n\t\tif (pFields[Index].FieldID == SR_FIELD_KEYWORDS) GetKeywords(pFields[Index], (CListBox *) pWnd);\r\n\t}\r\n\t\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::GetUIFieldData()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - bool GetKeywords (FieldInfo, pListBox);\r\n *\r\n *=========================================================================*\/\r\nbool CSrRecordDialog::GetKeywords(sruirecfields_t& FieldInfo, CListBox* pListBox)\r\n{\r\n\tCString\t\t\tBuffer; \r\n\tCSrIdRecord*\tpRecord;\r\n\tCSrSubrecord*\tpSubrecord;\r\n\r\n\tif (GetOutputRecord()->GetParent() == NULL) return false;\r\n\r\n\tpSubrecord = GetOutputRecord()->FindSubrecord(SR_NAME_KSIZ);\r\n\r\n\tif (pSubrecord == NULL) \r\n\t{\r\n\t\tpSubrecord = GetOutputRecord()->AddNewSubrecord(SR_NAME_KSIZ);\r\n\t\tif (pSubrecord == NULL) return AddSrGeneralError(\"Failed to find or create KSIZ subrecord!\");\r\n\t\tpSubrecord->InitializeNew();\r\n\t}\r\n\t\t\r\n\tCSrDwordSubrecord* pFormIdCount = SrCastClass(CSrDwordSubrecord, pSubrecord);\r\n\tif (pFormIdCount == NULL) return AddSrGeneralError(\"Invalid keyword count subrecord type!\");\r\n\r\n\tpSubrecord = GetOutputRecord()->FindSubrecord(SR_NAME_KWDA);\r\n\r\n\tif (pSubrecord == NULL) \r\n\t{\r\n\t\tpSubrecord = GetOutputRecord()->AddNewSubrecord(SR_NAME_KWDA);\r\n\t\tif (pSubrecord == NULL) return AddSrGeneralError(\"Failed to find or create KWDA subrecord!\");\r\n\t\tpSubrecord->InitializeNew();\r\n\t}\r\n\r\n\tCSrFormidArraySubrecord* pFormIDs = SrCastClass(CSrFormidArraySubrecord, pSubrecord);\r\n\tif (pFormIDs == NULL) return AddSrGeneralError(\"Cannot add keywords to non-formid array!\");\r\n\tpFormIDs->GetFormIDArray().Empty();\r\n\r\n\tfor (int i = 0; i < pListBox->GetCount(); ++i)\r\n\t{\r\n\t\tpListBox->GetText(i, Buffer);\r\n\t\tif (Buffer.IsEmpty()) continue;\r\n\t\t\t\r\n\t\tpRecord = GetOutputRecord()->GetParent()->FindEditorID(Buffer);\r\n\t\tif (pRecord == NULL) continue;\r\n\r\n\t\tpFormIDs->GetFormIDArray().Add(pRecord->GetFormID());\r\n\t}\r\n\r\n\tpFormIdCount->SetValue(pFormIDs->GetFormIDArray().GetSize());\r\n\treturn true;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::GetKeywords()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void InitToolTips (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::InitToolTips (void) {\r\n sruirecfields_t* pFields;\r\n CString\t Buffer;\r\n CWnd*\t\t pWnd;\r\n dword\t\t Index;\r\n int\t\t Result;\r\n\r\n pFields = GetUIFields();\r\n if (pFields == NULL) return;\r\n\r\n for (Index = 0; pFields[Index].FieldID != SR_FIELD_NONE; ++Index) {\r\n if (pFields[Index].ToolTipID == 0) continue;\r\n\r\n pWnd = GetDlgItem(pFields[Index].ControlID);\r\n if (pWnd == NULL) continue;\r\n\r\n Result = Buffer.LoadString(pFields[Index].ToolTipID);\r\n if (Result) m_ToolTip.AddTool(pWnd, Buffer);\r\n }\r\n\r\n\t\/* Add more fields *\/\r\n for (Index = 0; s_ToolTipInfo[Index].ControlID != 0; ++Index) {\r\n pWnd = GetDlgItem(s_ToolTipInfo[Index].ControlID);\r\n if (pWnd == NULL) continue;\r\n\r\n Result = Buffer.LoadString(s_ToolTipInfo[Index].StringID);\r\n if (Result) m_ToolTip.AddTool(pWnd, Buffer);\r\n }\r\n\r\n m_ToolTip.SetMaxTipWidth(300);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::InitToolTips()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDestroy ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDestroy() \r\n{\r\n\tCFormView::OnDestroy();\r\n\tif (m_pDlgHandler != NULL) m_pDlgHandler->RemoveFrame(GetParentFrame());\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDestroy()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnInitialUpdate (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnInitialUpdate (void) \r\n{\r\n\tCFormView::OnInitialUpdate();\r\n\tResizeParentToFit(FALSE);\r\n\t\r\n\tm_ToolTip.Create(this, 0);\r\n\tInitToolTips();\r\n\tm_ToolTip.Activate(TRUE);\r\n\tm_ToolTip.SetDelayTime(TTDT_AUTOPOP, 30000);\r\n\t\r\n\tassert(m_pDlgHandler != NULL);\r\n\t\r\n\t\t\/* Load the accelerator table if present *\/\r\n\tif (m_AcceleratorID != 0) m_hAccelerator = LoadAccelerators(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(m_AcceleratorID));\r\n\t\r\n\tm_EditInfo.IsHandled = false;\r\n\tm_EditInfo.NeedsIndex = false;\r\n\t\r\n\tCopyConditions();\r\n\tCopyScriptData();\r\n\t \r\n\tif (m_InitialSetData) SetControlData();\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnInitialUpdate()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - int OnPreSaveRecord (void);\r\n *\r\n *=========================================================================*\/\r\nint CSrRecordDialog::OnPreSaveRecord (void) {\r\n int Result;\r\n\r\n\t\/* This shouldn't happen... *\/\r\n if (m_pDlgHandler == NULL) {\r\n AddSrGeneralError(\"Parent dialog handler for record dialog has not been set!\");\r\n return (SR_RESULT_ERROR);\r\n }\r\n\r\n \/* Update the editorid from the UI (do not save to record), check for validity *\/\r\n Result = UpdateEditorID();\r\n if (Result < 0) return (Result);\r\n \r\n Result = m_pDlgHandler->OnPreSaveRecord(m_EditInfo);\r\n if (Result < 0) return (Result);\r\n\r\n if (m_pRecordHandler != NULL && !m_EditInfo.IsNew && !m_EditInfo.IsCopy) {\r\n m_pRecordHandler->GetEventHandler().SendPreUpdateEvent(m_EditInfo.pOldRecord, SR_EVENTFLAG_NONOTIFYSOURCE, (long) this);\r\n }\r\n\r\n return (SR_RESULT_OK);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnPreSaveRecord()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - int OnPostSaveRecord (void);\r\n *\r\n *=========================================================================*\/\r\nint CSrRecordDialog::OnPostSaveRecord (void) {\r\n \r\n if (m_pDlgHandler != NULL) {\r\n m_pDlgHandler->OnPostSaveRecord(m_EditInfo);\r\n }\r\n\r\n return (SR_RESULT_OK);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnPostSaveRecord()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - int OnCancelEditRecord (void);\r\n *\r\n *=========================================================================*\/\r\nint CSrRecordDialog::OnCancelEditRecord (void) {\r\n \r\n if (m_pDlgHandler != NULL) {\r\n m_pDlgHandler->OnCancelEditRecord(m_EditInfo);\r\n }\r\n\r\n return (SR_RESULT_OK);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnCancelEditRecord()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSave (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSave (void) {\r\n int Result;\r\n\r\n Result = OnPreSaveRecord();\r\n\r\n if (Result < 0) {\r\n if (Result != SR_RESULT_USERABORT) SrEditShowLastError(\"Failed to save the record changes!\");\r\n return;\r\n }\r\n\r\n GetControlData();\r\n\r\n Result = OnPostSaveRecord();\r\n\r\n if (Result < 0) {\r\n SrEditShowLastError(\"Failed to save the record changes!\");\r\n return;\r\n }\r\n\r\n GetDocument()->SetModifiedFlag(TRUE);\r\n Close();\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSave()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnCancel (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnCancel (void) {\r\n int Result;\r\n\r\n Result = OnCancelEditRecord();\r\n if (Result < 0) return;\r\n\r\n Close();\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnCancel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnApply ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnApply() {\r\n int Result;\r\n\r\n Result = OnPreSaveRecord();\r\n\r\n if (Result < 0) {\r\n if (Result != SR_RESULT_USERABORT) SrEditShowLastError(\"Failed to apply the record changes!\");\r\n return;\r\n }\r\n\r\n GetControlData();\r\n\r\n Result = OnPostSaveRecord();\r\n\r\n if (Result < 0) {\r\n SrEditShowLastError(\"Failed to apply the record changes!\");\r\n return;\r\n }\r\n\r\n\t\/* Reset the edit information *\/\r\n m_EditInfo.pOldRecord = m_EditInfo.pNewRecord;\r\n m_EditInfo.pNewRecord = NULL;\r\n m_EditInfo.HasUpdatedID = false;\r\n m_EditInfo.IsCopy = false;\r\n m_EditInfo.IsRenamed = false;\r\n m_EditInfo.IsNew = false;\r\n m_EditInfo.IsHandled = false;\r\n m_EditInfo.NeedsIndex = false;\r\n\r\n GetDocument()->SetModifiedFlag(TRUE);\r\n\r\n\t\/* Do another update *\/\r\n SetControlData();\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnApply()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnUpdate (pSender, lHint, pHint);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) {\r\n\r\n switch (lHint) {\r\n case SREDIT_DOC_HINT_UPDATERECORD:\r\n\tbreak;\r\n default:\r\n\tCFormView::OnUpdate(pSender, lHint, pHint);\r\n\tbreak;\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnUpdate()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - BOOL PreTranslateMessage (pMsg);\r\n *\r\n *=========================================================================*\/\r\nBOOL CSrRecordDialog::PreTranslateMessage (MSG* pMsg) {\r\n int Result;\r\n\r\n m_ToolTip.RelayEvent(pMsg);\r\n\r\n if (m_hAccelerator != NULL) {\r\n if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST && m_hAccelerator != NULL) {\r\n Result = TranslateAccelerator(m_hWnd, m_hAccelerator, pMsg);\r\n if (Result != 0) return (Result);\r\n }\r\n }\r\n\t\r\n return CFormView::PreTranslateMessage(pMsg);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::PreTranslateMessage()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void SetControlData (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::SetControlData (void) { \r\n CSString Buffer;\r\n bool Result;\r\n\r\n Result = GetInputRecord()->GetField(Buffer, SR_FIELD_EDITORID);\r\n\r\n if (Result)\r\n SetTitle(Buffer);\r\n else\r\n SetTitle(\"\");\r\n\r\n\t\/* Ignore invalid records *\/\r\n if (GetInputRecord() == NULL) {\r\n ClearControlData();\r\n return;\r\n }\r\n\r\n SetScriptControlData();\r\n SetUIFieldData();\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::SetControlData()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void SetEditInfo (InputInfo);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::SetEditInfo (sreditrecinfo_t& InputInfo) {\r\n m_EditInfo.HasUpdatedID = InputInfo.HasUpdatedID;\r\n m_EditInfo.IsCopy = InputInfo.IsCopy;\r\n m_EditInfo.IsNew = InputInfo.IsNew;\r\n m_EditInfo.IsRenamed = InputInfo.IsRenamed;\r\n m_EditInfo.NewEditorID = InputInfo.NewEditorID;\r\n m_EditInfo.pNewRecord = InputInfo.pNewRecord;\r\n m_EditInfo.pOldRecord = InputInfo.pOldRecord;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::SetEditInfo()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void SetTitle (pEditorID);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::SetTitle (const SSCHAR* pEditorID) {\r\n CString Buffer;\r\n bool IsActive = false;\r\n\r\n if (GetInputRecord() != NULL) IsActive = GetInputRecord()->IsActive();\r\n\r\n Buffer.Format(\"%s -- %s -- %s %s\", m_pDlgHandler->GetTitle(), GetTitlePrefix(), pEditorID == NULL ? \"\" : pEditorID, IsActive ? \"*\" : \"\");\r\n\r\n \/\/SetWindowText(Buffer);\r\n \/\/SetInternalWindowText(GetParentFrame()->m_hWnd, Buffer);\r\n\r\n CWnd* pWnd = GetParentFrame();\r\n\r\n if (pWnd != NULL && pWnd->IsKindOf(RUNTIME_CLASS(CFrameWnd))) {\r\n CFrameWnd* pFrame = (CFrameWnd *) pWnd;\r\n pFrame->SetTitle(Buffer);\r\n pFrame->SetWindowText(Buffer);\r\n }\r\n\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::SetTitle()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - bool SetKeywords (FieldInfo, pListBox);\r\n *\r\n *=========================================================================*\/\r\nbool CSrRecordDialog::SetKeywords(sruirecfields_t& FieldInfo, CListBox* pListBox)\r\n{\r\n\tCSrRecord*\t\tpRecord;\r\n\tCString\t\t\tBuffer;\r\n\tCSrFormidArraySubrecord* pKeywords;\r\n\tint\t\t\t\tListResult;\r\n\r\n\tif (GetInputRecord()->GetParent() == NULL || pListBox == NULL) return false;\r\n\t\t\t\r\n\tpListBox->ResetContent();\r\n\r\n\tpKeywords = SrCastClassNull(CSrFormidArraySubrecord, GetInputRecord()->FindSubrecord(SR_NAME_KWDA));\r\n\tif (pKeywords == NULL) return false;\r\n\r\n\tfor (dword i = 0; i < pKeywords->GetFormIDArray().GetSize(); ++i)\r\n\t{\r\n\t\tsrformid_t FormID = pKeywords->GetFormIDArray()[i];\r\n\t\tpRecord = GetInputRecord()->GetParent()->FindFormID(FormID);\r\n\t\tCSrIdRecord* pIdRecord = SrCastClassNull(CSrIdRecord, pRecord);\r\n\r\n\t\tif (pRecord == NULL || pIdRecord == NULL)\r\n\t\t{\r\n\t\t\tBuffer.Format(\"0x%08X\", FormID);\r\n\t\t\tListResult = pListBox->AddString(Buffer);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tListResult = pListBox->AddString(pIdRecord->GetEditorID());\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::SetKeywords()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - void SetUIFieldData (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::SetUIFieldData (void) {\r\n sruirecfields_t* pFields;\r\n CButton*\t\t\tpButton;\r\n CEdit*\t\t\tpEdit;\r\n CComboBox*\t\tpComboBox;\r\n CSString\t\t\tBuffer;\r\n CWnd*\t\t\t\tpWnd;\r\n dword\t\t\t\tIndex;\r\n bool\t\t\t\tResult;\r\n\r\n pFields = GetUIFields();\r\n if (pFields == NULL) return;\r\n\r\n for (Index = 0; pFields[Index].FieldID != SR_FIELD_NONE; ++Index) {\r\n pWnd = this->GetDlgItem(pFields[Index].ControlID);\r\n\r\n if (pWnd == NULL) \r\n\t{\t\r\n\t\tif (m_pTabControl != NULL) pWnd = m_pTabControl->FindChild(pFields[Index].ControlID);\r\n\t\tif (pWnd == NULL) continue;\r\n\t}\r\n\r\n\t\t\/* Save special fields for later use *\/\r\n switch (pFields[Index].FieldID) {\r\n\t case SR_FIELD_KEYWORDS:\t m_pKeywordsField = pWnd; break;\r\n case SR_FIELD_EDITORID: m_pEditorIDField = pWnd; break;\r\n case SR_FIELD_BIPED: m_pBipedPartsField = pWnd; break;\r\n case SR_FIELD_ENCHANTMENT: m_pEnchantField = pWnd; break;\r\n case SR_FIELD_MODEL: m_pModelField = pWnd; m_pMaleBipedModelField = pWnd; break;\r\n case SR_FIELD_ICON: m_pIconField = pWnd; m_pMaleIconField = pWnd; break;\r\n case SR_FIELD_SOUNDFILE: m_pSoundFileField = pWnd; break;\r\n case SR_FIELD_SOUND: m_pSoundField = pWnd; break;\r\n case SR_FIELD_MODEL2: m_pMaleWorldModelField = pWnd; break;\r\n case SR_FIELD_MODEL3: m_pFemaleBipedModelField = pWnd; break;\r\n case SR_FIELD_MODEL4: m_pFemaleWorldModelField = pWnd; break;\r\n case SR_FIELD_ICON2: m_pFemaleIconField = pWnd; break;\r\n\t case SR_FIELD_CONDITIONCOUNT: m_pConditionField = pWnd; break;\r\n\t case SR_FIELD_DROPSOUND: m_pDropSoundField = pWnd; break;\r\n\t case SR_FIELD_PICKUPSOUND: m_pPickupSoundField = pWnd; break;\r\n\t case SR_FIELD_BOUNDS: \r\n\t\t m_pBoundsField = pWnd; \r\n\t\t CSrIdRecord* pIdRecord = SrCastClass(CSrIdRecord, GetInputRecord());\r\n\t\t if (pIdRecord && pIdRecord->GetBoundsData()) m_BoundsCopy = *pIdRecord->GetBoundsData();\r\n\t\t break;\t\t \r\n }\r\n\r\n Result = GetInputRecord()->GetField(Buffer, pFields[Index].FieldID);\r\n if (!Result) continue;\r\n\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n pEdit = (CEdit *) pWnd;\r\n if (pFields[Index].MaxLength > 0) pEdit->SetLimitText(pFields[Index].MaxLength);\r\n pWnd->SetWindowText(Buffer);\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CComboBox))) {\r\n pComboBox = (CComboBox *) pWnd;\r\n FindComboBoxString(*pComboBox, Buffer, true);\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CButton))) {\r\n pButton = (CButton *) pWnd;\r\n\r\n\t if ((pButton->GetButtonStyle() & BS_CHECKBOX) !=0 )\r\n\t {\r\n\t\tpButton->SetCheck(tolower(Buffer[0]) == 't');\r\n\r\n\t }\r\n\t else \r\n\t {\r\n\t\t pButton->SetWindowTextA(Buffer);\r\n\t }\r\n\r\n }\r\n\telse if (pWnd->IsKindOf(RUNTIME_CLASS(CListBox))) {\r\n\t\tif (pFields[Index].FieldID == SR_FIELD_KEYWORDS) SetKeywords(pFields[Index], (CListBox *) pWnd);\r\n\t}\r\n\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::SetUIFieldData()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Method - int UpdateEditorID (void);\r\n *\r\n *=========================================================================*\/\r\nint CSrRecordDialog::UpdateEditorID (void) {\r\n CString Buffer;\r\n\r\n m_EditInfo.NewEditorID.Empty();\r\n m_EditInfo.HasUpdatedID = false;\r\n\r\n if (m_pEditorIDField != NULL) {\r\n m_pEditorIDField->GetWindowText(Buffer);\r\n m_EditInfo.NewEditorID = Buffer;\r\n\r\n SrPrepareEditorID(m_EditInfo.NewEditorID);\r\n }\r\n\r\n return (SR_RESULT_OK);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Method CSrRecordDialog::UpdateEditorID()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnKillfocusEditorid ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnKillfocusEditorid() {\r\n CString Buffer;\r\n CSString TempString;\r\n\r\n if (m_pEditorIDField != NULL) {\r\n m_pEditorIDField->GetWindowText(Buffer);\r\n TempString = Buffer;\r\n\r\n SrPrepareEditorID(TempString);\r\n\r\n m_pEditorIDField->SetWindowText(TempString);\r\n }\r\n\t\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnKillfocusEditorid()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnBipedpartsButton ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnBipedpartsButton() {\r\n\t\/*\r\n CString Buffer;\r\n CSString TempString;\r\n bool Result;\r\n dword Parts;\r\n\r\n if (m_pBipedPartsField == NULL) return;\r\n\r\n m_pBipedPartsField->GetWindowText(Buffer);\r\n Parts = ParseObBipedFlagString(Buffer, \",\");\r\n\r\n \/\/Result = SrEditBipedParts(Parts);\r\n Result = SrEditBipedPartsList(Parts);\r\n \r\n MakeObBipedFlagString(TempString, Parts, \", \");\r\n m_pBipedPartsField->SetWindowText(TempString);\r\n *\/\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnBipedpartsButton()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnEditEnchantment ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnEditEnchantment() {\r\n CString Buffer;\r\n CSrRecord* pRecord;\r\n\r\n if (m_pEnchantField == NULL || m_pDlgHandler == NULL || m_pDlgHandler == NULL) return;\r\n m_pEnchantField->GetWindowText(Buffer);\r\n\r\n if (Buffer.IsEmpty()) {\r\n m_pDlgHandler->EditNewRecord(SR_NAME_ENCH);\r\n }\r\n else {\r\n pRecord = m_pRecordHandler->FindEditorID(Buffer);\r\n if (pRecord != NULL) m_pDlgHandler->EditRecord(pRecord);\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditEnchantment()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectScript ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectScript() {\r\n\/*\r\n CString Buffer;\r\n bool Result;\r\n\r\n if (m_pScriptField == NULL) return;\r\n m_pScriptField->GetWindowText(Buffer);\r\n \r\n switch (m_ScriptType) {\r\n case SR_SCRIPTTYPE_OBJECT: Result = m_pDlgHandler->SelectItemScript(Buffer); break;\r\n case SR_SCRIPTTYPE_QUEST: Result = false; break;\r\n case SR_SCRIPTTYPE_MAGICEFFECT: Result = false; break;\r\n default: Result = false; break;\r\n }\r\n\r\n if (Result) m_pScriptField->SetWindowText(Buffer);\r\n *\/\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectScript()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectEnchantment ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectEnchantment() \r\n{\r\n\tCString Buffer;\r\n\tbool Result;\r\n\r\n\tif (m_pEnchantField == NULL) return;\r\n\tm_pEnchantField->GetWindowText(Buffer);\r\n\r\n\tResult = m_pDlgHandler->SelectRecord(Buffer, SR_NAME_ENCH, &CSrEnchRecord::s_FieldMap);\r\n\r\n\t\/*\r\n\tswitch (m_EnchantType) {\r\n\t\tcase SR_ENCHTYPE_APPAREL: Result = m_pDlgHandler->SelectApparelEnchant(Buffer); break;\r\n\t\tcase SR_ENCHTYPE_WEAPON: Result = m_pDlgHandler->SelectWeaponEnchant(Buffer); break;\r\n\t\tcase SR_ENCHTYPE_STAFF: Result = m_pDlgHandler->SelectStaffEnchant(Buffer); break;\r\n\t\tcase SR_ENCHTYPE_SCROLL: Result = m_pDlgHandler->SelectScrollEnchant(Buffer); break;\r\n\t\tdefault: Result = false; break;\r\n\t} *\/\r\n\r\n\tif (Result) m_pEnchantField->SetWindowText(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectEnchantment()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnActivateView (BOOL bActivate, CView* pActivateView, CView* pDeactiveView);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnActivateView (BOOL bActivate, CView* pActivateView, CView* pDeactiveView) {\r\n\r\n if (bActivate && pActivateView != NULL) {\r\n AfxGetMainWnd()->SendMessage(SRE_MSG_UPDATEUNDO, (WPARAM) &m_pRecordHandler->GetUndoItems(), 0);\r\n }\r\n else if (pActivateView != NULL) {\r\n }\r\n\r\n CFormView::OnActivateView(bActivate, pActivateView, pDeactiveView);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnActivateView()\r\n *=========================================================================*\/\r\n\r\n \r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - LRESULT OnEditRecordMsg (wParam, lParam);\r\n *\r\n *=========================================================================*\/\r\nLRESULT CSrRecordDialog::OnEditRecordMsg (WPARAM wParam, LPARAM lParam) {\r\n CSrRecord* pRecord = (CSrRecord *) wParam;\r\n sreditrecinfo_t EditInfo;\r\n\r\n if (pRecord == NULL) return (0);\r\n if (m_NoActivateRecord) return (0);\r\n if (m_pDlgHandler == NULL) return (0);\r\n \r\n EditInfo.HasUpdatedID = false;\r\n EditInfo.IsCopy = false;\r\n EditInfo.IsNew = false;\r\n EditInfo.IsRenamed = false;\r\n EditInfo.pNewRecord = NULL;\r\n EditInfo.pOldRecord = pRecord;\r\n EditInfo.NewEditorID.Empty();\r\n\r\n m_pDlgHandler->EditRecord(EditInfo);\r\n\r\n return (0);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditRecordMsg()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropEnchant (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropEnchant (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srrldroprecords_t* pDropItems = (srrldroprecords_t *) pNotifyStruct;\r\n CSrRecord*\t pRecord;\r\n CSrEnchRecord* pEnchant;\r\n\r\n *pResult = SRRL_DROPCHECK_ERROR;\r\n if (m_pEnchantField == NULL) return;\r\n if (pDropItems->pRecords == NULL) return;\r\n if (pDropItems->pRecords->GetSize() != 1) return;\r\n\r\n pRecord = pDropItems->pRecords->GetAt(0);\r\n\r\n if (pRecord->GetRecordType() != SR_NAME_ENCH) return;\r\n pEnchant = SrCastClass(CSrEnchRecord, pRecord);\r\n if (pEnchant == NULL) return;\r\n \/\/if (pEnchant->GetType() != m_EnchantType) return;\r\n\r\n if (pDropItems->Notify.code == ID_SRRECORDLIST_DROP) \r\n {\r\n m_pEnchantField->SetWindowText(pEnchant->GetEditorID());\r\n }\r\n\r\n *pResult = SRRL_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropEnchant()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnEditCut (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnEditCut (void) {\r\n CWnd* pWnd = GetFocus();\r\n\r\n if (pWnd == NULL) return;\r\n\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n CEdit* pEdit = (CEdit *) pWnd;\r\n pEdit->Cut();\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n CRichEditCtrl* pRichEdit = (CRichEditCtrl *) pWnd;\r\n pRichEdit->Cut();\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditCut()\r\n *=========================================================================*\/\r\n \r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnEditCopy (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnEditCopy (void) {\r\n CWnd* pWnd = GetFocus();\r\n\r\n if (pWnd == NULL) return;\r\n\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n CEdit* pEdit = (CEdit *) pWnd;\r\n pEdit->Copy();\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n CRichEditCtrl* pRichEdit = (CRichEditCtrl *) pWnd;\r\n pRichEdit->Copy();\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditCopy()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnEditPaste (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnEditPaste (void) {\r\n CWnd* pWnd = GetFocus();\r\n\r\n if (pWnd == NULL) return;\r\n\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n CEdit* pEdit = (CEdit *) pWnd;\r\n pEdit->Paste();\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n CRichEditCtrl* pRichEdit = (CRichEditCtrl *) pWnd;\r\n pRichEdit->Paste();\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditPaste()\r\n *=========================================================================*\/\r\n\r\n \r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnEditSelectAll (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnEditSelectAll (void) {\r\n CWnd* pWnd = GetFocus();\r\n\r\n if (pWnd == NULL) return;\r\n\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n CEdit* pEdit = (CEdit *) pWnd;\r\n pEdit->SetSel(0, pEdit->GetWindowTextLength());\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n CRichEditCtrl* pRichEdit = (CRichEditCtrl *) pWnd;\r\n pRichEdit->SetSel(0, pRichEdit->GetWindowTextLength());\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CListCtrl))) {\r\n CListCtrl* pList = (CListCtrl *) pWnd;\r\n\r\n for (int Index = 0; Index < pList->GetItemCount(); ++Index) {\r\n pList->SetItemState(Index, LVIS_SELECTED, LVIS_SELECTED);\r\n }\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditSelectAll()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnUpdateEditSelectAll (pCmdUI);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnUpdateEditSelectAll (CCmdUI* pCmdUI) {\r\n CWnd* pWnd = GetFocus();\r\n bool EnableCmd = false;\r\n\r\n if (pWnd != NULL) {\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n EnableCmd = true;\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n EnableCmd = true;\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CListCtrl))) {\r\n EnableCmd = true;\r\n }\r\n }\r\n\r\n pCmdUI->Enable(EnableCmd);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnUpdateEditSelectAll()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnUpdateEditPaste (pCmdUI);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnUpdateEditPaste (CCmdUI* pCmdUI) {\r\n CWnd* pWnd = GetFocus();\r\n bool EnableCmd = false;\r\n\r\n if (pWnd != NULL) {\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n EnableCmd = true;\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n EnableCmd = true;\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CListCtrl))) {\r\n EnableCmd = false;\r\n }\r\n }\r\n\r\n pCmdUI->Enable(EnableCmd);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnUpdateEditPaste()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnUpdateEditCopy (pCmdUI);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnUpdateEditCopy (CCmdUI* pCmdUI) {\r\n CWnd* pWnd = GetFocus();\r\n bool EnableCmd = false;\r\n\r\n if (pWnd != NULL) {\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n CEdit* pEdit = (CEdit *) pWnd;\r\n int StartSel;\r\n int EndSel;\r\n pEdit->GetSel(StartSel, EndSel);\r\n if (EndSel > StartSel) EnableCmd = true;\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n CRichEditCtrl* pRichEdit = (CRichEditCtrl *) pWnd;\r\n if (pRichEdit->GetSelectionType() != SEL_EMPTY) EnableCmd = true;\r\n }\r\n }\r\n\r\n pCmdUI->Enable(EnableCmd);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnUpdateEditCopy()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnEditUndo (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnEditUndo (void) {\r\n CWnd* pWnd = GetFocus();\r\n\r\n if (pWnd == NULL) return;\r\n\r\n if (pWnd->IsKindOf(RUNTIME_CLASS(CEdit))) {\r\n CEdit* pEdit = (CEdit *) pWnd;\r\n pEdit->Undo();\r\n }\r\n else if (pWnd->IsKindOf(RUNTIME_CLASS(CRichEditCtrl))) {\r\n CRichEditCtrl* pRichEdit = (CRichEditCtrl *) pWnd;\r\n pRichEdit->Undo();\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditUndo()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - BOOL OnHelpInfo (pHelpInfo);\r\n *\r\n *=========================================================================*\/\r\nBOOL CSrRecordDialog::OnHelpInfo (HELPINFO* pHelpInfo) {\r\n \r\n m_pDlgHandler->OnHelp(this, pHelpInfo);\r\n\r\n return (true);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnHelpInfo()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnHelp (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnHelp (void) \r\n{\r\n m_pDlgHandler->OnHelp(this, NULL);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnHelp()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropModel (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropModel (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pModelField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_NIF) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_MESHES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pModelField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropMaleWorldModel (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropMaleWorldModel (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pMaleWorldModelField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_NIF) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_MESHES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pMaleWorldModelField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropMaleWorldModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropMaleBipedModel (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropMaleBipedModel (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pMaleBipedModelField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_NIF) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_MESHES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pMaleBipedModelField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropMaleBipedModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropFemaleWorldModel (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropFemaleWorldModel (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pFemaleWorldModelField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_NIF) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_MESHES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pFemaleWorldModelField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropFemaleWorldModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropFemaleBipedModel (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropFemaleBipedModel (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pFemaleBipedModelField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_NIF) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_MESHES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pFemaleBipedModelField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropFemaleBipedModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropIcon (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropIcon (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pIconField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_IMAGE) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_TEXTURES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pIconField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropIcon()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropMaleIcon (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropMaleIcon (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pMaleIconField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_IMAGE) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_TEXTURES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pMaleIconField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropMaleIcon()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropFemaleIcon (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropFemaleIcon (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pFemaleIconField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_IMAGE) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_TEXTURES)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pFemaleIconField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropFemaleIcon()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropSoundFile (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropSoundFile (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n if (m_pSoundFileField == NULL) return;\r\n if (pDropInfo->pResourceFile == NULL) return;\r\n if (pDropInfo->pResourceFile->GetResourceType() != SR_RESOURCETYPE_SOUND) return;\r\n if (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_SOUNDS)) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) {\r\n m_pSoundFileField->SetWindowText(pDropInfo->pResourceFile->GetCSName()); \r\n }\r\n\r\n *pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropSoundFile()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectModel (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectModel (void) {\r\n CString Buffer;\r\n\r\n if (m_pModelField == NULL) return;\r\n m_pModelField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectModel(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectIcon (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectIcon (void) {\r\n CString Buffer;\r\n\r\n if (m_pIconField == NULL) return;\r\n m_pIconField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectIcon(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectIcon()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectSoundFile (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectSoundFile (void) {\r\n CString Buffer;\r\n\r\n if (m_pSoundFileField == NULL) return;\r\n m_pSoundFileField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectSoundFile(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectSoundFile()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectMaleIcon (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectMaleIcon (void) {\r\n CString Buffer;\r\n\r\n if (m_pMaleIconField == NULL) return;\r\n m_pMaleIconField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectIcon(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectMaleIcon()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectFemaleIcon (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectFemaleIcon (void) {\r\n CString Buffer;\r\n\r\n if (m_pFemaleIconField == NULL) return;\r\n m_pFemaleIconField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectIcon(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectMaleIcon()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectMaleWorldModel (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectMaleWorldModel (void) {\r\n CString Buffer;\r\n\r\n if (m_pMaleWorldModelField == NULL) return;\r\n m_pMaleWorldModelField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectModel(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectMaleWorldModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectMaleBipedModel (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectMaleBipedModel (void) {\r\n CString Buffer;\r\n\r\n if (m_pMaleBipedModelField == NULL) return;\r\n m_pMaleBipedModelField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectModel(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectMaleBipedModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectFemaleWorldModel (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectFemaleWorldModel (void) {\r\n CString Buffer;\r\n\r\n if (m_pFemaleWorldModelField == NULL) return;\r\n m_pFemaleWorldModelField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectModel(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectFemaleWorldModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectFemaleBipedModel (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectFemaleBipedModel (void) {\r\n CString Buffer;\r\n\r\n if (m_pFemaleBipedModelField == NULL) return;\r\n m_pFemaleBipedModelField->GetWindowText(Buffer);\r\n\r\n m_pDlgHandler->SelectModel(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectFemaleBipedModel()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnSelectsoundButton ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnSelectsoundButton() {\r\n CString Buffer;\r\n bool Result;\r\n\r\n if (m_pSoundField == NULL) return;\r\n m_pSoundField->GetWindowText(Buffer);\r\n\r\n Result = m_pDlgHandler->SelectSound(Buffer);\r\n if (Result) m_pSoundField->SetWindowText(Buffer);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnSelectsoundButton()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnEditSound ();\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnEditSound() {\r\n CString Buffer;\r\n CSrRecord* pRecord;\r\n\r\n if (m_pSoundField == NULL) return;\r\n if (m_pRecordHandler == NULL || m_pDlgHandler == NULL) return;\r\n m_pSoundField->GetWindowText(Buffer);\r\n\r\n if (Buffer.IsEmpty()) {\r\n m_pDlgHandler->EditNewRecord(SR_NAME_SOUN);\r\n }\r\n else {\r\n pRecord = m_pRecordHandler->FindEditorID(Buffer);\r\n if (pRecord != NULL) m_pDlgHandler->EditRecord(pRecord);\r\n }\r\n\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnEditSound()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropSound (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropSound (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srrldroprecords_t* pDropItems = (srrldroprecords_t *) pNotifyStruct;\r\n CSrRecord*\t pRecord;\r\n CSrIdRecord* pSound;\r\n\r\n *pResult = SRRL_DROPCHECK_ERROR;\r\n if (m_pSoundField == NULL) return;\r\n if (pDropItems->pRecords == NULL) return;\r\n if (pDropItems->pRecords->GetSize() != 1) return;\r\n\r\n pRecord = pDropItems->pRecords->GetAt(0);\r\n\r\n\t\/* Ignore any invalid record types *\/\r\n if (pRecord->GetRecordType() != SR_NAME_SOUN) return;\r\n pSound = SrCastClass(CSrIdRecord, pRecord);\r\n if (pSound == NULL) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropItems->Notify.code == ID_SRRECORDLIST_DROP) \r\n {\r\n m_pSoundField->SetWindowText(pSound->GetEditorID());\r\n }\r\n\r\n *pResult = SRRL_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropSound()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropDropSound (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropDropSound (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srrldroprecords_t* pDropItems = (srrldroprecords_t *) pNotifyStruct;\r\n CSrRecord*\t pRecord;\r\n CSrIdRecord* pSound;\r\n\r\n *pResult = SRRL_DROPCHECK_ERROR;\r\n if (m_pDropSoundField == NULL) return;\r\n if (pDropItems->pRecords == NULL) return;\r\n if (pDropItems->pRecords->GetSize() != 1) return;\r\n\r\n pRecord = pDropItems->pRecords->GetAt(0);\r\n\r\n\t\/* Ignore any invalid record types *\/\r\n if (pRecord->GetRecordType() != SR_NAME_SNDR) return;\r\n pSound = SrCastClass(CSrIdRecord, pRecord);\r\n if (pSound == NULL) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropItems->Notify.code == ID_SRRECORDLIST_DROP) {\r\n m_pDropSoundField->SetWindowText(pSound->GetEditorID());\r\n }\r\n\r\n *pResult = SRRL_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropDropSound()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnDropPickupSound (pNotifyStruct, pResult);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnDropPickupSound (NMHDR* pNotifyStruct, LRESULT* pResult) {\r\n srrldroprecords_t* pDropItems = (srrldroprecords_t *) pNotifyStruct;\r\n CSrRecord*\t pRecord;\r\n CSrIdRecord* pSound;\r\n\r\n *pResult = SRRL_DROPCHECK_ERROR;\r\n if (m_pPickupSoundField == NULL) return;\r\n if (pDropItems->pRecords == NULL) return;\r\n if (pDropItems->pRecords->GetSize() != 1) return;\r\n\r\n pRecord = pDropItems->pRecords->GetAt(0);\r\n\r\n\t\/* Ignore any invalid record types *\/\r\n if (pRecord->GetRecordType() != SR_NAME_SNDR) return;\r\n pSound = SrCastClass(CSrIdRecord, pRecord);\r\n if (pSound == NULL) return;\r\n\r\n\t\/* If we're just checking or not *\/\r\n if (pDropItems->Notify.code == ID_SRRECORDLIST_DROP) {\r\n m_pPickupSoundField->SetWindowText(pSound->GetEditorID());\r\n }\r\n\r\n *pResult = SRRL_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnDropPickupSound()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnBnClickedAddkeywordButton (void);\r\n *\r\n *=========================================================================*\/\r\n void CSrRecordDialog::OnBnClickedAddkeywordButton()\r\n {\r\n\t CWnd*\t\tpWnd;\r\n\t CListBox*\tpList;\r\n\t CString Buffer;\r\n\t int\t\tIndex;\r\n\t bool\t\tResult;\r\n\r\n\t pWnd = GetDlgItem(IDC_KEYWORDS);\r\n\t if (pWnd == NULL) return;\r\n\r\n\t pList = static_cast(pWnd);\r\n\t if (pList == NULL) return;\r\n\r\n\t Result = m_pDlgHandler->SelectKeyword(Buffer);\r\n\t if (!Result) return;\r\n\t \r\n\t Index = pList->AddString(Buffer);\r\n\t pList->SetCurSel(Index);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnBnClickedAddkeywordButton()\r\n *=========================================================================*\/\r\n\r\n\r\nvoid CSrRecordDialog::OnEditBaseKeyword()\r\n{\r\n\tCWnd*\t\tpWnd;\r\n\tCListBox*\tpList;\r\n\tCString\t\tBuffer;\r\n\r\n\tif (m_pDlgHandler == NULL) return;\r\n\r\n\tif (m_pKeywordsField == NULL)\r\n\t{\r\n\t\tpWnd = GetDlgItem(IDC_KEYWORDS);\r\n\t\tif (pWnd == NULL) return;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpWnd = m_pKeywordsField;\r\n\t}\r\n\r\n\tpList = static_cast(pWnd);\r\n\tif (pList == NULL) return;\r\n\r\n\tm_pDlgHandler->EditRecordHelper(*pList, SR_NAME_KYWD);\r\n}\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnBnClickedEditkeywordButton (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnBnClickedEditkeywordButton()\r\n{\r\n\tCWnd*\t\tpWnd;\r\n\tCListBox*\tpList;\r\n\tCString\t\tBuffer;\r\n\tint\t\t\tIndex;\r\n\tbool\t\tResult;\r\n\r\n \tif ((GetKeyState(VK_CONTROL) & 0x8000) != 0)\r\n\t{\r\n\t\tOnEditBaseKeyword();\r\n\t\treturn;\r\n\t}\r\n\r\n\tpWnd = GetDlgItem(IDC_KEYWORDS);\r\n\tif (pWnd == NULL) return;\r\n\r\n\tpList = static_cast(pWnd);\r\n\tif (pList == NULL) return;\r\n\r\n\tIndex = pList->GetCurSel();\r\n\tif (Index < 0) return;\r\n\r\n\tpList->GetText(Index, Buffer);\r\n\r\n\tResult = m_pDlgHandler->SelectKeyword(Buffer);\r\n\tif (!Result) return;\r\n\t \r\n\tpList->DeleteString(Index);\r\n\tif (!Buffer.IsEmpty()) Index = pList->AddString(Buffer);\r\n\tpList->SetCurSel(Index);\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnBnClickedEditkeywordButton()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnBnClickedDelkeywordButton (void);\r\n *\r\n *=========================================================================*\/\r\n void CSrRecordDialog::OnBnClickedDelkeywordButton()\r\n {\r\n\t CWnd*\t\tpWnd;\r\n\t CListBox*\tpList;\r\n\t int\t\tIndex;\r\n\r\n\t pWnd = GetDlgItem(IDC_KEYWORDS);\r\n\t if (pWnd == NULL) return;\r\n\r\n\t pList = static_cast(pWnd);\r\n\t if (pList == NULL) return;\r\n\r\n\t Index = pList->GetCurSel();\r\n\t if (Index < 0) return;\r\n\r\n\t pList->DeleteString(Index);\r\n\t pList->SetCurSel(Index);\r\n }\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnBnClickedDelkeywordButton()\r\n *=========================================================================*\/\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void OnLbnSelchangeKeywords (void);\r\n *\r\n *=========================================================================*\/\r\nvoid CSrRecordDialog::OnLbnSelchangeKeywords()\r\n{\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::OnLbnSelchangeKeywords()\r\n *=========================================================================*\/\r\n\r\n\r\nsrconditioninfo_t* CSrRecordDialog::CreateConditionInfo (CSrCtdaSubrecord* pCondition, CSrRecord* pRecord, const dword Index)\r\n{\r\n\tsrconditioninfo_t* pNewCond;\r\n\tCSrSubrecord* pSubrecord;\r\n\r\n\tpNewCond = new srconditioninfo_t;\r\n\tpNewCond->Condition.Copy(pCondition);\r\n\tm_ConditionsCopy.Add(pNewCond);\r\n\r\n\tpSubrecord = pRecord->GetSubrecord(Index+1);\r\n\tif (pSubrecord == NULL) return pNewCond;\r\n\r\n\tif (pSubrecord->GetRecordType() == SR_NAME_CIS1)\r\n\t{\r\n\t\tpNewCond->pParam1 = new CSrStringSubrecord;\r\n\t\tpNewCond->pParam1->Initialize(SR_NAME_CIS1, 1);\r\n\t\tpNewCond->pParam1->Copy(pSubrecord);\r\n\t}\r\n\telse if (pSubrecord->GetRecordType() == SR_NAME_CIS2)\r\n\t{\r\n\t\tpNewCond->pParam2 = new CSrStringSubrecord;\r\n\t\tpNewCond->pParam2->Initialize(SR_NAME_CIS2, 1);\r\n\t\tpNewCond->pParam2->Copy(pSubrecord);\r\n\t}\r\n\r\n\tpSubrecord = pRecord->GetSubrecord(Index+2);\r\n\tif (pSubrecord == NULL) return pNewCond;\r\n\r\n\tif (pSubrecord->GetRecordType() == SR_NAME_CIS2 && pNewCond->pParam2 == NULL)\r\n\t{\r\n\t\tpNewCond->pParam2 = new CSrStringSubrecord;\r\n\t\tpNewCond->pParam2->Initialize(SR_NAME_CIS2, 1);\r\n\t\tpNewCond->pParam2->Copy(pSubrecord);\r\n\t}\r\n\r\n\treturn pNewCond;\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::CopyConditions (void) \r\n{\r\n\tif (GetInputRecord() == NULL) return;\r\n\tif (m_IgnoreConditions) return;\r\n\r\n\tfor (dword i = 0; i < GetInputRecord()->GetNumSubrecords(); ++i)\r\n\t{\r\n\t\tCSrSubrecord* pSubrecord = GetInputRecord()->GetSubrecord(i);\r\n\t\tif (pSubrecord->GetRecordType() != SR_NAME_CTDA) continue;\r\n\r\n\t\tCSrCtdaSubrecord* pCondition = SrCastClassNull(CSrCtdaSubrecord, pSubrecord);\r\n\t\tif (pCondition != NULL) CreateConditionInfo(pCondition, GetInputRecord(), i);\r\n\t}\r\n\r\n\tm_ConditionsChanged = false;\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::SaveConditions (void) \r\n{\r\n\tif (!m_ConditionsChanged) return;\r\n\tif (GetOutputRecord() == NULL) return;\r\n\tif (m_IgnoreConditions) return;\r\n\r\n\tGetOutputRecord()->DeleteSubrecords(SR_NAME_CTDA);\r\n\tGetOutputRecord()->DeleteSubrecords(SR_NAME_CIS1);\r\n\tGetOutputRecord()->DeleteSubrecords(SR_NAME_CIS2);\r\n\r\n\tfor (dword i = 0; i < m_ConditionsCopy.GetSize(); ++i)\r\n\t{\r\n\t\tsrconditioninfo_t* pCondition = m_ConditionsCopy[i];\r\n\t\t\r\n\t\tif (pCondition != NULL) \r\n\t\t{\r\n\t\t\tCSrSubrecord* pNewCond = GetOutputRecord()->AddNewSubrecord(SR_NAME_CTDA);\r\n\t\t\tif (pNewCond) pNewCond->Copy(&pCondition->Condition);\r\n\r\n\t\t\tif (pCondition->pParam1)\r\n\t\t\t{\r\n\t\t\t\tCSrSubrecord* pNewParam = GetOutputRecord()->AddNewSubrecord(SR_NAME_CIS1);\r\n\t\t\t\tif (pNewParam) pNewParam->Copy(pCondition->pParam1);\r\n\t\t\t}\r\n\r\n\t\t\tif (pCondition->pParam2)\r\n\t\t\t{\r\n\t\t\t\tCSrSubrecord* pNewParam = GetOutputRecord()->AddNewSubrecord(SR_NAME_CIS2);\r\n\t\t\t\tif (pNewParam) pNewParam->Copy(pCondition->pParam2);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnEditFind()\r\n{\r\n\tif (m_pDlgHandler) m_pDlgHandler->OpenFind();\t\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedConditionButton()\r\n{\r\n\tif (m_pConditionField == NULL) return;\r\n\r\n\tCSrConditionDlg ConditionDlg;\r\n\tint Result = ConditionDlg.DoModal(GetInputRecord(), &m_ConditionsCopy);\r\n\tif (Result == IDOK) m_ConditionsChanged = true;\r\n\r\n\tCString Buffer;\r\n\tBuffer.Format(\"%d\", m_ConditionsCopy.GetSize());\r\n\tm_pConditionField->SetWindowText(Buffer);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedSelectdropsoundButton()\r\n{\r\n\tif (m_pDlgHandler == NULL || m_pDropSoundField == NULL) return;\r\n\tCString Buffer;\r\n\r\n\tm_pDropSoundField->GetWindowText(Buffer);\r\n\tif (!m_pDlgHandler->SelectRecord(Buffer, SR_NAME_SNDR, &CSrSndrRecord::s_FieldMap)) return;\r\n\tm_pDropSoundField->SetWindowText(Buffer);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedSelectpickupButton()\r\n{\r\n\tif (m_pDlgHandler == NULL || m_pPickupSoundField == NULL) return;\r\n\tCString Buffer;\r\n\r\n\tm_pPickupSoundField->GetWindowText(Buffer);\r\n\tif (!m_pDlgHandler->SelectRecord(Buffer, SR_NAME_SNDR, &CSrSndrRecord::s_FieldMap)) return;\r\n\tm_pPickupSoundField->SetWindowText(Buffer);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedEditDropsound()\r\n{\r\n\tif (m_pDlgHandler && m_pDropSoundField) m_pDlgHandler->EditRecordHelper(m_pDropSoundField, SR_NAME_SNDR);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedEditPickupsound()\r\n{\r\n\tif (m_pDlgHandler && m_pPickupSoundField) m_pDlgHandler->EditRecordHelper(m_pPickupSoundField, SR_NAME_SNDR);\r\n}\r\n\r\n\r\n\r\n\/*===========================================================================\r\n *\r\n * Class CSrRecordDialog Event - void DropRecordHelper ();\r\n *\r\n *=========================================================================*\/\r\nint CSrRecordDialog::DropRecordHelper (srrldroprecords_t* pDropItems, CWnd* pWnd, const srrectype_t AllowedType, const int AllowedCount) {\r\n\tCSrRecord*\t pRecord;\r\n\tCSrIdRecord* pIdRecord;\r\n \r\n\tif (pWnd == NULL || pDropItems == NULL) return SRRL_DROPCHECK_ERROR;\r\n\tif (pDropItems->pRecords == NULL) return SRRL_DROPCHECK_ERROR;\r\n\tif ((int) pDropItems->pRecords->GetSize() > AllowedCount) return SRRL_DROPCHECK_ERROR;\r\n\r\n\tpRecord = pDropItems->pRecords->GetAt(0);\r\n\r\n\t\t\/* Ignore any invalid record types *\/\r\n\tif (pRecord->GetRecordType() != AllowedType) return SRRL_DROPCHECK_ERROR;\r\n\tpIdRecord = SrCastClass(CSrIdRecord, pRecord);\r\n\tif (pIdRecord == NULL) return SRRL_DROPCHECK_ERROR;\r\n\r\n\t\t\/* If we're just checking or not *\/\r\n\tif (pDropItems->Notify.code == ID_SRRECORDLIST_DROP) \r\n\t{\r\n\t\tpWnd->SetWindowText(pIdRecord->GetEditorID());\r\n\t}\r\n\t\r\n\treturn SRRL_DROPCHECK_OK;\r\n}\r\n\/*===========================================================================\r\n *\t\tEnd of Class Event CSrRecordDialog::DropRecordHelper()\r\n *=========================================================================*\/\r\n\r\n\r\nint CSrRecordDialog::DropRecordHelper (srrldroprecords_t* pDropItems, CListBox& ListBox, const srrectype_t AllowedType, const bool PermitDuplicates) {\r\n\tCSrRecord*\t pRecord;\r\n\tCSrIdRecord* pIdRecord;\r\n \r\n\tif (pDropItems == NULL) return SRRL_DROPCHECK_ERROR;\r\n\tif (pDropItems->pRecords == NULL) return SRRL_DROPCHECK_ERROR;\r\n\r\n\tfor (dword i = 0; i < pDropItems->pRecords->GetSize(); ++i)\r\n\t{\r\n\t\tpRecord = pDropItems->pRecords->GetAt(i);\r\n\r\n\t\t\t\/* Ignore any invalid record types *\/\r\n\t\tif (pRecord->GetRecordType() != AllowedType) return SRRL_DROPCHECK_ERROR;\r\n\t\tpIdRecord = SrCastClass(CSrIdRecord, pRecord);\r\n\t\tif (pIdRecord == NULL) return SRRL_DROPCHECK_ERROR;\r\n\r\n\t\t\t\/* If we're just checking or not *\/\r\n\t\tif (pDropItems->Notify.code == ID_SRRECORDLIST_DROP) \r\n\t\t{\r\n\t\t\tif (PermitDuplicates)\r\n\t\t\t{\r\n\t\t\t\tListBox.AddString(pIdRecord->GetEditorID());\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (ListBox.FindString(-1, pIdRecord->GetEditorID()) < 0) ListBox.AddString(pIdRecord->GetEditorID());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn SRRL_DROPCHECK_OK;\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnDropKeywords (NMHDR* pNotifyStruct, LRESULT* pResult) \r\n{\r\n\tsrrldroprecords_t* pDropItems = (srrldroprecords_t *) pNotifyStruct;\r\n\tCSrRecord*\t pRecord;\r\n\tCSrIdRecord* pIdRecord;\r\n\tCListBox*\t\t pListBox;\r\n\r\n\t*pResult = SRRL_DROPCHECK_ERROR;\r\n\r\n\tif (m_pKeywordsField == NULL) return;\r\n\tif (!m_pKeywordsField->IsKindOf(RUNTIME_CLASS(CListBox))) return;\r\n\r\n\tif (pDropItems == NULL) return;\r\n\tif (pDropItems->pRecords == NULL) return;\r\n\t\r\n\tpListBox = (CListBox *) m_pKeywordsField;\r\n\r\n\tfor (dword i = 0; i < pDropItems->pRecords->GetSize(); ++i)\r\n\t{\r\n\t\tpRecord = pDropItems->pRecords->GetAt(i);\r\n\r\n\t\t\t\/* Ignore any invalid record types *\/\r\n\t\tif (pRecord->GetRecordType() != SR_NAME_KYWD) return;\r\n\t\tpIdRecord = SrCastClass(CSrIdRecord, pRecord);\r\n\t\tif (pIdRecord == NULL) return;\r\n\r\n\t\t\t\/* If we're just checking or not *\/\r\n\t\tif (pDropItems->Notify.code == ID_SRRECORDLIST_DROP) \r\n\t\t{\r\n\t\t\tif (pListBox->FindString(-1, pIdRecord->GetEditorID()) < 0) pListBox->AddString(pIdRecord->GetEditorID());\r\n\t\t}\r\n\t}\r\n\t\r\n\t*pResult = SRRL_DROPCHECK_OK;\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedBounds()\r\n{\r\n\tCString Buffer;\r\n\r\n\tif (m_pBoundsField == NULL) return;\r\n\tif (!SrEditBoundsDlg(m_BoundsCopy)) return;\r\n\r\n\tBuffer.Format(\"(%hd, %hd, %hd) (%hd, %hd, %hd)\", \r\n\t\tm_BoundsCopy.X1, m_BoundsCopy.Y1, m_BoundsCopy.Z1,\r\n\t\tm_BoundsCopy.X2, m_BoundsCopy.Y2, m_BoundsCopy.Z2);\r\n\tm_pBoundsField->SetWindowText(Buffer);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)\r\n{\r\n\tCFormView::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);\r\n\tOnInitMenuPopupHelper(this, pPopupMenu, nIndex, bSysMenu);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::GetScriptControlData (void)\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::SetScriptControlData (void)\r\n{\r\n\tCSrVmadScriptArray& Scripts = m_ScriptDataCopy.GetScriptData().Scripts;\r\n\tCString Buffer;\r\n\tint ListIndex;\r\n\r\n\tif (m_pScriptList == NULL) return;\r\n\tm_pScriptList->ResetContent();\r\n\t\r\n\tfor (dword i = 0; i < Scripts.GetSize(); ++i)\r\n\t{\r\n\t\tListIndex = m_pScriptList->AddString(Scripts[i]->Name.c_str());\r\n\t\tif (ListIndex >= 0) m_pScriptList->SetItemDataPtr(ListIndex, Scripts[i]);\r\n\t}\r\n\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::SaveScriptData (void)\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\tdword ScriptCount = m_pScriptList->GetCount();\r\n\r\n\tif (GetOutputRecord() == NULL) return;\r\n\r\n\tif (ScriptCount == 0)\r\n\t{\r\n\t\tGetOutputRecord()->DeleteSubrecords(SR_NAME_VMAD);\r\n\t\treturn;\r\n\t}\r\n\r\n\tCSrSubrecord* pSubrecord = GetOutputRecord()->FindSubrecord(SR_NAME_VMAD);\r\n\tif (pSubrecord == NULL) pSubrecord = GetOutputRecord()->AddInitNewSubrecord(SR_NAME_VMAD);\r\n\tCSrVmadSubrecord* pScriptData = SrCastClassNull(CSrVmadSubrecord, pSubrecord);\r\n\tif (pScriptData == NULL) return;\r\n\r\n\tpScriptData->Copy(&m_ScriptDataCopy);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::CopyScriptData (void)\r\n{\r\n\tm_ScriptDataCopy.Initialize(SR_NAME_VMAD, 6);\r\n\tm_ScriptDataCopy.InitializeNew();\r\n\r\n\tif (GetInputRecord() == NULL) return;\r\n\r\n\tCSrSubrecord* pSubrecord = GetInputRecord()->FindSubrecord(SR_NAME_VMAD);\r\n\tCSrVmadSubrecord* pScriptData = SrCastClassNull(CSrVmadSubrecord, pSubrecord);\r\n\tif (pScriptData == NULL) return;\r\n\r\n\tm_ScriptDataCopy.Copy(pScriptData);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedAddscript()\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tCSrSelectScriptDlg Dlg;\r\n\tCString ScriptName;\r\n\r\n\tint Result = Dlg.DoModal(ScriptName);\r\n\tif (Result != IDOK) return;\r\n\tif (ScriptName.IsEmpty()) return;\r\n\r\n\tsrvmadscript_t* pScript = m_ScriptDataCopy.GetScriptData().Scripts.AddNew();\r\n\tpScript->Name = ScriptName;\r\n\r\n\tint ListIndex = m_pScriptList->AddString(ScriptName);\r\n\tif (ListIndex >= 0) m_pScriptList->SetItemData(ListIndex, (DWORD) pScript);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedEditpropertiesscript()\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tif (m_pScriptList->GetCount() <= 0 || m_pScriptList->GetSelCount() <= 0) return;\r\n\tint ListIndex = m_pScriptList->GetCurSel();\r\n\tif (ListIndex < 0) return;\r\n\r\n\tsrvmadscript_t* pScript = (srvmadscript_t *) m_pScriptList->GetItemDataPtr(ListIndex);\r\n\tif (pScript == NULL) return;\r\n\r\n\tCSrScriptPropertyDlg Dlg;\r\n\r\n\tbool Result = Dlg.DoModal(*pScript, m_pRecordHandler);\r\n\tif (!Result) return;\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedEditscript()\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tif (m_pScriptList->GetCount() <= 0 || m_pScriptList->GetSelCount() <= 0) return;\r\n\tint ListIndex = m_pScriptList->GetCurSel();\r\n\tif (ListIndex < 0) return;\r\n\r\n\tsrvmadscript_t* pScript = (srvmadscript_t *) m_pScriptList->GetItemDataPtr(ListIndex);\r\n\tif (pScript == NULL) return;\r\n\r\n\tbool Result = GetSrEditApp().EditScriptName(pScript->Name, true);\r\n\tif (!Result) SrEditShowError(\"Failed to open the script editor for '%s'!\", pScript->Name.c_str());\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnBnClickedDelscript()\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tif (m_pScriptList->GetCount() <= 0 || m_pScriptList->GetSelCount() <= 0) return;\r\n\tint ListIndex = m_pScriptList->GetCurSel();\r\n\tif (ListIndex < 0) return;\r\n\r\n\tsrvmadscript_t* pScript = (srvmadscript_t *) m_pScriptList->GetItemDataPtr(ListIndex);\r\n\tif (pScript == NULL) return;\r\n\r\n\tm_ScriptDataCopy.GetScriptData().Scripts.Delete(pScript);\r\n\tm_pScriptList->DeleteString(ListIndex);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnLbnDblclkScripts()\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tif ((GetKeyState(VK_CONTROL) & 0x8000) != 0)\r\n\t{\r\n\t\tOnBnClickedEditscript();\r\n\t\treturn;\r\n\t}\r\n\r\n\tOnBnClickedEditpropertiesscript();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnScriptrecordAddNew()\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tCString ScriptName;\r\n\tif (!GetSrEditApp().CreateNewScript(ScriptName)) return;\r\n\t\t\r\n\tAddScript(ScriptName);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnScriptrecordAdd()\r\n{\r\n\tOnBnClickedAddscript();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnScriptrecordEditProperties()\r\n{\r\n\tOnBnClickedEditpropertiesscript();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnScriptrecordEditScript()\r\n{\r\n\tOnBnClickedEditscript();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnScriptrecordDelete()\r\n{\r\n\tOnBnClickedDelscript();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnUpdateScriptrecordExists(CCmdUI *pCmdUI)\r\n{\r\n\tpCmdUI->Enable(m_pScriptList != NULL && m_pScriptList->GetCurSel() >= 0);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnContextMenu(CWnd* pWnd, CPoint Point)\r\n {\r\n \tCMenu Menu;\r\n\tCMenu* pSubMenu;\r\n\tint Result;\r\n\t\r\n\tif (pWnd == m_pScriptList) \r\n\t{\r\n\t\t\t\t\/* Force select item on right-click *\/\r\n\t\tBOOL Outside;\r\n\t\tCPoint ClientPt(Point);\r\n\t\tm_pScriptList->ScreenToClient(&ClientPt);\r\n\t\tUINT ListIndex = m_pScriptList->ItemFromPoint(ClientPt, Outside);\r\n\t\tif (!Outside) m_pScriptList->SetSel(ListIndex, TRUE);\r\n\t\t\r\n\t\tResult = Menu.LoadMenu(IDR_SCRIPTRECORD_MENU);\r\n\t\tif (!Result) return;\r\n\t\t\r\n\t\tpSubMenu = Menu.GetSubMenu(0);\r\n\t\tif (pSubMenu == NULL) return;\r\n\t\t\r\n\t\tpSubMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, Point.x, Point.y, this, NULL);\r\n\t}\r\n\telse if (pWnd == m_pKeywordsField)\r\n\t{\r\n\t\t\t\/* Force select item on right-click *\/\r\n\t\tBOOL Outside;\r\n\t\tCPoint ClientPt(Point);\r\n\t\t\r\n\t\tCListBox* pList = static_cast(m_pKeywordsField);\r\n\t\tif (pList == NULL) return;\r\n\r\n\t\tpList->ScreenToClient(&ClientPt);\r\n\t\tUINT ListIndex = pList->ItemFromPoint(ClientPt, Outside);\r\n\t\tif (!Outside) pList->SetCurSel(ListIndex);\r\n\r\n\t\tCMenu Menu;\r\n\t\tBOOL Result = Menu.LoadMenu(IDR_KEYWORDRECORD_MENU);\r\n\t\tif (!Result) return;\r\n\t\t\r\n\t\tCMenu* pSubMenu = Menu.GetSubMenu(0);\r\n\t\tif (pSubMenu == NULL) return;\r\n\t\t\r\n\t\tpSubMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, Point.x, Point.y, this, NULL);\r\n\t}\r\n\telse if (pWnd == m_pConditionField) \r\n\t{\r\n\t\tResult = Menu.LoadMenu(IDR_CONDITIONRECORD_MENU);\r\n\t\tif (!Result) return;\r\n\t\t\r\n\t\tpSubMenu = Menu.GetSubMenu(0);\r\n\t\tif (pSubMenu == NULL) return;\r\n\t\t\r\n\t\tpSubMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, Point.x, Point.y, this, NULL);\r\n\t}\r\n\telse \r\n\t{\r\n\t\tCFormView::OnContextMenu(pWnd, Point);\r\n\t}\r\n\t \r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnDropScript (NMHDR* pNotifyStruct, LRESULT* pResult) \r\n{\r\n\tsrresourcedropinfo_t* pDropInfo = (srresourcedropinfo_t *) pNotifyStruct;\r\n\t*pResult = SRRESOURCE_DROPCHECK_ERROR;\r\n\r\n\tif (m_pScriptList == NULL) return;\r\n\tif (pDropInfo->pResourceFile == NULL) return;\r\n\tif (!pDropInfo->pResourceFile->IsInPath(SRRESOURCE_PATH_SCRIPTS)) return;\r\n\r\n\tCSString Filename(pDropInfo->pResourceFile->GetFullName());\r\n\tCSString ScriptName;\r\n\r\n\tif (strnicmp(Filename, \"scripts\\\\source\\\\\", 14) == 0)\r\n\t{\r\n\t\tif (!Filename.EndsWithI(\".psc\")) return;\r\n\t\tScriptName = pDropInfo->pResourceFile->GetName();\r\n\t\tScriptName.TruncateAtR('.');\r\n\t}\r\n\telse if (strnicmp(Filename, \"scripts\\\\\", 7) == 0)\r\n\t{\r\n\t\tif (!Filename.EndsWithI(\".pex\")) return;\r\n\t\tScriptName = pDropInfo->pResourceFile->GetName();\r\n\t\tScriptName.TruncateAtR('.');\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tsrvmadscript_t* pScriptData = m_ScriptDataCopy.FindScript(ScriptName);\r\n\tif (pScriptData != NULL) return;\r\n\r\n\t\t\/* If we're just checking or not *\/\r\n\tif (pDropInfo->Notify.code == ID_SRRESOURCE_DROP) \r\n\t{\r\n\t\tAddScript(ScriptName);\r\n\t}\r\n\r\n\t*pResult = SRRESOURCE_DROPCHECK_OK;\r\n}\r\n\r\n\r\nbool CSrRecordDialog::AddScript (const char* pScriptName)\r\n{\r\n\tif (m_pScriptList == NULL) return false;\r\n\r\n\tsrvmadscript_t* pNewScript = m_ScriptDataCopy.GetScriptData().Scripts.AddNew();\r\n\tpNewScript->Name = pScriptName;\r\n\r\n\tint ListIndex = m_pScriptList->AddString(pScriptName);\r\n\tif (ListIndex >= 0) m_pScriptList->SetItemDataPtr(ListIndex, pNewScript);\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnScriptrecordCopyscripts()\r\n{\r\n\tint SelIndex[256];\r\n\tint SelCount;\r\n\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tSelCount = m_pScriptList->GetSelItems(250, SelIndex);\r\n\r\n\tif (SelCount == LB_ERR)\r\n\t{\r\n\t\tSelIndex[0] = m_pScriptList->GetCurSel();\r\n\t\tSelCount = 1;\r\n\t}\r\n\r\n\tSrGlobClipClearScripts();\r\n\r\n\tfor (int i = 0; i < SelCount; ++i)\r\n\t{\r\n\t\tsrvmadscript_t* pScript = m_ScriptDataCopy.GetScriptData().Scripts[i];\r\n\t\tif (pScript == NULL) continue;\r\n\t\tSrGlobClipAddScript(pScript);\r\n\t}\r\n\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnScriptrecordPastescripts()\r\n{\r\n\tif (m_pScriptList == NULL) return;\r\n\r\n\tfor (dword i = 0; i < SrGlobClipGetScripts().GetSize(); ++i)\r\n\t{\r\n\t\tsrvmadscript_t* pScript = SrGlobClipGetScripts()[i];\r\n\t\tif (m_ScriptDataCopy.FindScript(pScript->Name) != NULL) continue;\r\n\r\n\t\tm_ScriptDataCopy.GetScriptData().Scripts.AddNew()->Copy(*pScript);\r\n\t}\r\n\r\n\tSetScriptControlData();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnUpdateScriptrecordCopyscripts(CCmdUI *pCmdUI)\r\n{\r\n\tpCmdUI->Enable(m_pScriptList && m_pScriptList->GetSelCount() > 0);\r\n\r\n\tCString Buffer;\r\n\tBuffer.Format(\"Copy %d Script(s)\", m_pScriptList->GetSelCount());\r\n\tpCmdUI->SetText(Buffer);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnUpdateScriptrecordPastescripts(CCmdUI *pCmdUI)\r\n{\r\n\tpCmdUI->Enable(m_pScriptList && SrGlobClipGetScripts().GetSize() > 0);\r\n\r\n\tCString Buffer;\r\n\tBuffer.Format(\"Paste %d Script(s)\", SrGlobClipGetScripts().GetSize());\r\n\tpCmdUI->SetText(Buffer);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnConditionrecordCopy()\r\n{\r\n\tif (m_pConditionField == NULL || m_IgnoreConditions) return;\r\n\tif (m_ConditionsCopy.GetSize() == 0) return;\r\n\r\n\tSrGlobClipClearConditions();\r\n\r\n\tfor (dword i = 0; i < m_ConditionsCopy.GetSize(); ++i)\r\n\t{\r\n\t\tSrGlobClipAddCondition(m_ConditionsCopy[i]);\r\n\t}\r\n\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnConditionrecordPaste()\r\n{\r\n\tif (m_pConditionField == NULL || m_IgnoreConditions) return;\r\n\tif (SrGlobClipGetConditions().GetSize() == 0) return;\r\n\tm_ConditionsChanged = true;\r\n\r\n\tfor (dword i = 0; i < SrGlobClipGetConditions().GetSize(); ++i)\r\n\t{\r\n\t\tm_ConditionsCopy.AddNew()->Copy(*SrGlobClipGetConditions()[i]);\r\n\t}\r\n\r\n\tCString Buffer;\r\n\tBuffer.Format(\"%d\", m_ConditionsCopy.GetSize());\r\n\tm_pConditionField->SetWindowTextA(Buffer);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnConditionrecordDeleteAll()\r\n{\r\n\tif (m_pConditionField == NULL || m_IgnoreConditions) return;\r\n\tif (m_ConditionsCopy.GetSize() > 0) m_ConditionsChanged = true;\r\n\tm_ConditionsCopy.Destroy();\t\r\n\tm_pConditionField->SetWindowText(\"0\");\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnUpdateConditionrecordCopy(CCmdUI *pCmdUI)\r\n{\r\n\tif (m_pConditionField == NULL || m_IgnoreConditions)\r\n\t{\r\n\t\tpCmdUI->Enable(false);\r\n\t\treturn;\r\n\t}\r\n\r\n\tCString Buffer;\r\n\tBuffer.Format(\"Copy %d Condition(s)\", m_ConditionsCopy.GetSize());\r\n\tpCmdUI->SetText(Buffer);\r\n\tpCmdUI->Enable(m_ConditionsCopy.GetSize() > 0);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnUpdateConditionrecordPaste(CCmdUI *pCmdUI)\r\n{\r\n\tif (m_pConditionField == NULL || m_IgnoreConditions)\r\n\t{\r\n\t\tpCmdUI->Enable(false);\r\n\t\treturn;\r\n\t}\r\n\r\n\tCString Buffer;\r\n\tBuffer.Format(\"Paste %d Condition(s)\", SrGlobClipGetConditions().GetSize());\r\n\tpCmdUI->SetText(Buffer);\r\n\tpCmdUI->Enable(SrGlobClipGetConditions().GetSize() > 0);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnUpdateConditionrecordDeleteAll(CCmdUI *pCmdUI)\r\n{\r\n\tif (m_pConditionField == NULL || m_IgnoreConditions)\r\n\t{\r\n\t\tpCmdUI->Enable(false);\r\n\t\treturn;\r\n\t}\r\n\r\n\tpCmdUI->Enable(m_ConditionsCopy.GetSize() > 0);\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnKeywordAdd()\r\n{\r\n\tOnBnClickedAddkeywordButton();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnKeywordEdit()\r\n{\r\n\tOnBnClickedEditkeywordButton();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnKeywordEditBase()\r\n{\r\n\tOnEditBaseKeyword();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnKeywordDelete()\r\n{\r\n\tOnBnClickedDelkeywordButton();\r\n}\r\n\r\n\r\nvoid CSrRecordDialog::OnUpdateKeywordEdit(CCmdUI *pCmdUI)\r\n{\r\n\tif (m_pKeywordsField == NULL)\r\n\t{\r\n\t\tpCmdUI->Enable(false);\r\n\t\treturn;\r\n\t}\r\n\r\n\tCListBox* pList = static_cast(m_pKeywordsField);\r\n\tpCmdUI->Enable(pList && pList->GetCurSel() >= 0);\r\n}\r\n\r\n","avg_line_length":33.9866666667,"max_line_length":151,"alphanum_fraction":0.5396183521} {"size":194,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"#include\n\nusing namespace std;\n\nint gcd(int a, int b) {\n\tif(a == 0) return b;\n\treturn gcd(b % a, a);\n}\nint main() {\n\tint a, b;\n\tcin >> a >> b;\n\tcout << gcd(a, b) << endl;\n\treturn 0;\n}\n","avg_line_length":12.9333333333,"max_line_length":27,"alphanum_fraction":0.5463917526} {"size":1563,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"#include \nusing namespace std;\n\nclass Node{\n public:\n int data;\n Node* next = NULL;\n Node(){this->data=0;}\n};\n\nvoid push_front(Node** head_ref, int const &new_data){\n Node* new_node = new Node();\n new_node->data = new_data;\n new_node->next = *head_ref;\n *head_ref = new_node;\n}\n\nvoid print_list(Node* head){\n printf(\"Linked list: \");\n while(head) {printf(\"%d \",head->data); head = head->next;}\n printf(\"\\n\");\n}\n\nNode* reverse(Node* node){\n Node *prev = NULL, *next = NULL;\n while(node){\n next = node->next;\n node->next = prev;\n prev = node;\n node = next;\n }\n return prev;\n}\n\nvoid partial_reverse(Node* head, size_t p, size_t q){\n if(p == q) return;\n Node *prev = head, *next = head, *temp = NULL;\n while(p-- > 2) prev = prev->next;\n while(q-- > 1) next = next->next;\n temp = next->next;\n next->next = NULL;\n next = temp;\n\n temp = prev->next;\n prev->next = reverse(prev->next);\n temp->next = next;\n}\n\nint main(){\n ios_base::sync_with_stdio(0);\n cin.tie(0), cout.tie(0);\n\n Node* head = NULL;\n int temp; size_t n, p, q;\n cout << \"Enter the p and q: \" << endl; cin >> p >> q;\n cout << \"Enter the number of nodes: \" << endl; cin >> n;\n assert(p<=n and q<=n);\n cout << \"Enter the nodes: \" << endl;\n while(n--) {\n cin >> temp;\n push_front(&head, temp);\n }\n\n printf(\"Before \");\n print_list(head);\n\n partial_reverse(head, p, q);\n printf(\"After \");\n print_list(head);\n\n return 0;\n}","avg_line_length":21.7083333333,"max_line_length":62,"alphanum_fraction":0.5431861804} {"size":378,"ext":"hpp","lang":"C++","max_stars_count":2.0,"content":"\/**\n * Copyright (c) Kolo Naukowe Elektronikow, Akademia Gorniczo-Hutnicza im. Stanislawa Staszica w Krakowie 2020\n * Authors: Arkadiusz Balys, Kamil Kasperczyk, Witold Lukasik\n *\n * HALina adc driver\n *\n *\/\n\n#pragma once\n\n#include \n\nnamespace halina {\n\n class ADC {\n public:\n virtual void init() = 0;\n\n virtual void startConversion() = 0;\n };\n}\n","avg_line_length":17.1818181818,"max_line_length":110,"alphanum_fraction":0.6587301587} {"size":363,"ext":"hh","lang":"C++","max_stars_count":null,"content":"#pragma once\n#include \"typed-geometry\/types\/vec.hh\"\n#include \"typed-geometry\/types\/pos.hh\"\n\nnamespace gamedev\n{\nstruct PointLight\n{\n alignas(16) tg::pos3 position;\n alignas(16) tg::vec3 color;\n float intensity;\n float radius;\n};\n\nstruct DirectionalLight\n{\n tg::vec3 direction;\n tg::vec3 color;\n};\n\nstruct AmbientLight\n{\n tg::vec3 color;\n};\n}\n","avg_line_length":13.9615384615,"max_line_length":38,"alphanum_fraction":0.6804407713} {"size":2137,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n\nvoid mnbins(double a1, double a2, int naa, double& bl, double& bh, int& nb, double& bwid) {\n\n\/\/*-*-*-*-*-*-*-*-*-*-*Compute reasonable histogram intervals*-*-*-*-*-*-*-*-*\n\/\/*-* ======================================\n\/\/*-* Function TO DETERMINE REASONABLE HISTOGRAM INTERVALS\n\/\/*-* GIVEN ABSOLUTE UPPER AND LOWER BOUNDS A1 AND A2\n\/\/*-* AND DESIRED MAXIMUM NUMBER OF BINS NAA\n\/\/*-* PROGRAM MAKES REASONABLE BINNING FROM BL TO BH OF WIDTH BWID\n\/\/*-* F. JAMES, AUGUST, 1974 , stolen for Minuit, 1988\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\n \/* Local variables *\/\n double awid,ah, al, sigfig, sigrnd, alb;\n int kwid, lwid, na=0, log_;\n\n al = a1 < a2 ? a1 : a2;\n\/\/ al = std::min(a1,a2);\n\/\/ ah = std::max(a1,a2);\n ah = a1 > a2 ? a1 : a2;\n if (al == ah) ah = al + 1;\n\n\/\/*-*- IF NAA .EQ. -1 , PROGRAM USES BWID INPUT FROM CALLING ROUTINE\n if (naa == -1) goto L150;\nL10:\n na = naa - 1;\n if (na < 1) na = 1;\n\n\/\/*-*- GET NOMINAL BIN WIDTH IN EXPON FORM\nL20:\n awid = (ah-al) \/ double(na);\n log_ = int(log10(awid));\n if (awid <= 1) --log_;\n sigfig = awid*pow(10.0, -log_);\n\/\/*-*- ROUND MANTISSA UP TO 2, 2.5, 5, OR 10\n if (sigfig > 2) goto L40;\n sigrnd = 2;\n goto L100;\nL40:\n if (sigfig > 2.5) goto L50;\n sigrnd = 2.5;\n goto L100;\nL50:\n if (sigfig > 5) goto L60;\n sigrnd = 5;\n goto L100;\nL60:\n sigrnd = 1;\n ++log_;\nL100:\n bwid = sigrnd*pow(10.0, log_);\n goto L200;\n\/\/*-*- GET NEW BOUNDS FROM NEW WIDTH BWID\nL150:\n if (bwid <= 0) goto L10;\nL200:\n alb = al \/ bwid;\n lwid = int(alb);\n if (alb < 0) --lwid;\n bl = bwid*double(lwid);\n alb = ah \/ bwid + 1;\n kwid = int(alb);\n if (alb < 0) --kwid;\n bh = bwid*double(kwid);\n nb = kwid - lwid;\n if (naa > 5) goto L240;\n if (naa == -1) return;\n\/\/*-*- REQUEST FOR ONE BIN IS DIFFICULT CASE\n if (naa > 1 || nb == 1) return;\n bwid *= 2;\n nb = 1;\n return;\nL240:\n if (nb << 1 != naa) return;\n ++na;\n goto L20;\n} \/* mnbins_ *\/\n","avg_line_length":27.0506329114,"max_line_length":91,"alphanum_fraction":0.4885353299} {"size":1746,"ext":"cc","lang":"C++","max_stars_count":24.0,"content":"\/\/\n\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include \"zetasql\/reference_impl\/functions\/uuid.h\"\n\n#include \"zetasql\/public\/functions\/uuid.h\"\n#include \"zetasql\/public\/value.h\"\n#include \"zetasql\/reference_impl\/function.h\"\n#include \"zetasql\/base\/statusor.h\"\n\nnamespace zetasql {\nnamespace {\nclass GenerateUuidFunction : public SimpleBuiltinScalarFunction {\n public:\n GenerateUuidFunction()\n : SimpleBuiltinScalarFunction(FunctionKind::kGenerateUuid,\n types::StringType()) {}\n zetasql_base::StatusOr Eval(absl::Span args,\n EvaluationContext* context) const override;\n};\n\nzetasql_base::StatusOr GenerateUuidFunction::Eval(\n absl::Span args, EvaluationContext* context) const {\n ZETASQL_RET_CHECK(args.empty());\n return Value::String(\n functions::GenerateUuid(*(context->GetRandomNumberGenerator())));\n}\n\n} \/\/ namespace\n\nvoid RegisterBuiltinUuidFunctions() {\n BuiltinFunctionRegistry::RegisterScalarFunction(\n {FunctionKind::kGenerateUuid},\n [](FunctionKind kind, const Type* output_type) {\n return new GenerateUuidFunction();\n });\n}\n\n} \/\/ namespace zetasql\n","avg_line_length":32.9433962264,"max_line_length":75,"alphanum_fraction":0.7187857961} {"size":6353,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/\/ Copyright \u00a9 2017-2021 Trust Wallet.\n\/\/\n\/\/ This file is part of Trust. The full Trust copyright notice, including\n\/\/ terms governing use, modification, and redistribution, is contained in the\n\/\/ file LICENSE at the root of the source code distribution tree.\n\n#include \n#include \n#include \n\n#include \"..\/Bitcoin\/Address.h\"\n#include \"..\/Bitcoin\/CashAddress.h\"\n#include \"..\/Bitcoin\/SegwitAddress.h\"\n#include \"..\/Cosmos\/Address.h\"\n#include \"..\/Decred\/Address.h\"\n#include \"..\/Kusama\/Address.h\"\n#include \"..\/Polkadot\/Address.h\"\n#include \"..\/Zcash\/TAddress.h\"\n#include \"..\/Zilliqa\/Address.h\"\n#include \"..\/Cardano\/AddressV3.h\"\n#include \"..\/NEO\/Address.h\"\n#include \"..\/Nano\/Address.h\"\n#include \"..\/Elrond\/Address.h\"\n#include \"..\/NEAR\/Address.h\"\n\n#include \"..\/Coin.h\"\n#include \"..\/HexCoding.h\"\n\nusing namespace TW;\n\nstruct TWAnyAddress {\n TWString* address;\n enum TWCoinType coin;\n};\n\nbool TWAnyAddressEqual(struct TWAnyAddress* _Nonnull lhs, struct TWAnyAddress* _Nonnull rhs) {\n return TWStringEqual(lhs->address, rhs->address) && lhs->coin == rhs->coin;\n}\n\nbool TWAnyAddressIsValid(TWString* _Nonnull string, enum TWCoinType coin) {\n const auto& address = *reinterpret_cast(string);\n return TW::validateAddress(coin, address);\n}\n\nstruct TWAnyAddress* _Nullable TWAnyAddressCreateWithString(TWString* _Nonnull string,\n enum TWCoinType coin) {\n const auto& address = *reinterpret_cast(string);\n auto normalized = TW::normalizeAddress(coin, address);\n if (normalized.empty()) { return nullptr; }\n return new TWAnyAddress{TWStringCreateWithUTF8Bytes(normalized.c_str()), coin};\n}\n\nstruct TWAnyAddress* _Nonnull TWAnyAddressCreateWithPublicKey(\n struct TWPublicKey* _Nonnull publicKey, enum TWCoinType coin) {\n auto address = TW::deriveAddress(coin, publicKey->impl);\n return new TWAnyAddress{TWStringCreateWithUTF8Bytes(address.c_str()), coin};\n}\n\nvoid TWAnyAddressDelete(struct TWAnyAddress* _Nonnull address) {\n TWStringDelete(address->address);\n delete address;\n}\n\nTWString* _Nonnull TWAnyAddressDescription(struct TWAnyAddress* _Nonnull address) {\n return TWStringCreateWithUTF8Bytes(TWStringUTF8Bytes(address->address));\n}\n\nenum TWCoinType TWAnyAddressCoin(struct TWAnyAddress* _Nonnull address) {\n return address->coin;\n}\n\nTWData* _Nonnull TWAnyAddressData(struct TWAnyAddress* _Nonnull address) {\n auto& string = *reinterpret_cast(address->address);\n Data data;\n switch (address->coin) {\n case TWCoinTypeBinance:\n case TWCoinTypeCosmos:\n case TWCoinTypeKava:\n case TWCoinTypeTerra:\n case TWCoinTypeBandChain:\n case TWCoinTypeTHORChain:\n case TWCoinTypeBluzelle:\n case TWCoinTypeIoTeX: {\n Cosmos::Address addr;\n if (!Cosmos::Address::decode(string, addr)) {\n break;\n }\n data = addr.getKeyHash();\n break;\n }\n\n case TWCoinTypeBitcoin:\n case TWCoinTypeBitcoinTestNet:\n case TWCoinTypeDigiByte:\n case TWCoinTypeGroestlcoin:\n case TWCoinTypeLitecoin:\n case TWCoinTypeViacoin: {\n auto decoded = Bitcoin::SegwitAddress::decode(string);\n if (!std::get<2>(decoded)) {\n break;\n }\n data = std::get<0>(decoded).witnessProgram;\n break;\n }\n\n case TWCoinTypeBitcoinCash: {\n auto addr = Bitcoin::CashAddress(string);\n data.resize(Bitcoin::Address::size);\n size_t outlen = 0;\n cash_data_to_addr(data.data(), &outlen, addr.bytes.data(), 34);\n data = Data(data.begin() + 1, data.end());\n break;\n }\n\n case TWCoinTypeDash:\n case TWCoinTypeDogecoin:\n case TWCoinTypeMonacoin:\n case TWCoinTypeQtum:\n case TWCoinTypeRavencoin:\n case TWCoinTypeZcoin: {\n auto addr = Bitcoin::Address(string);\n data = Data(addr.bytes.begin() + 1, addr.bytes.end());\n break;\n }\n\n case TWCoinTypeDecred: {\n auto addr = Decred::Address(string);\n data = Data(addr.bytes.begin() + 2, addr.bytes.end());\n break;\n }\n\n case TWCoinTypeZcash:\n case TWCoinTypeZelcash: {\n auto addr = Zcash::TAddress(string);\n data = Data(addr.bytes.begin() + 2, addr.bytes.end());\n break;\n }\n\n case TWCoinTypeCallisto:\n case TWCoinTypeEthereum:\n case TWCoinTypeEthereumClassic:\n case TWCoinTypeGoChain:\n case TWCoinTypePOANetwork:\n case TWCoinTypeThunderToken:\n case TWCoinTypeTomoChain:\n case TWCoinTypeVeChain:\n case TWCoinTypeTheta:\n case TWCoinTypeWanchain:\n case TWCoinTypeAion:\n case TWCoinTypeSmartChainLegacy:\n case TWCoinTypeSmartChain:\n case TWCoinTypePolygon:\n data = parse_hex(string);\n break;\n\n case TWCoinTypeNano: {\n auto addr = Nano::Address(string);\n data = Data(addr.bytes.begin(), addr.bytes.end());\n break;\n }\n\n case TWCoinTypeZilliqa: {\n Zilliqa::Address addr;\n if (!Zilliqa::Address::decode(string, addr)) {\n break;\n }\n \/\/ data in Zilliqa is a checksummed string without 0x\n auto str = Zilliqa::checksum(addr.getKeyHash());\n data = Data(str.begin(), str.end());\n break;\n }\n\n case TWCoinTypeKusama: {\n auto addr = Kusama::Address(string);\n data = Data(addr.bytes.begin() + 1, addr.bytes.end());\n break;\n }\n\n case TWCoinTypePolkadot: {\n auto addr = Polkadot::Address(string);\n data = Data(addr.bytes.begin() + 1, addr.bytes.end());\n break;\n }\n\n case TWCoinTypeCardano: {\n auto addr = Cardano::AddressV3(string);\n data = addr.data();\n break;\n }\n\n case TWCoinTypeNEO: {\n auto addr = NEO::Address(string);\n data = Data(addr.bytes.begin(), addr.bytes.end());\n break;\n }\n\n case TWCoinTypeElrond: {\n Elrond::Address addr;\n if (Elrond::Address::decode(string, addr)) {\n data = addr.getKeyHash();\n }\n \n break;\n }\n\n case TWCoinTypeNEAR: {\n auto addr = NEAR::Address(string);\n data = Data(addr.bytes.begin(), addr.bytes.end());\n break;\n }\n\n default: break;\n }\n return TWDataCreateWithBytes(data.data(), data.size());\n}\n","avg_line_length":29.412037037,"max_line_length":94,"alphanum_fraction":0.6513458209} {"size":8686,"ext":"cpp","lang":"C++","max_stars_count":1742.0,"content":"\/** @file mpoly-ginac.cpp\n *\n * This file implements several functions that work multivariate polynomials.\n*\/\n\/*\n * GiNaC Copyright (C) 1999-2008 Johannes Gutenberg University Mainz, Germany\n * (C) 2016 Ralf Stephan\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"ex.h\"\n#include \"normal.h\"\n#include \"mpoly.h\"\n#include \"upoly.h\"\n#include \"numeric.h\"\n#include \"operators.h\"\n#include \"utils.h\"\n#include \"symbol.h\"\n#include \"power.h\"\n#include \"add.h\"\n#include \"mul.h\"\n\nnamespace GiNaC {\n\n\n\/*\n * Computation of LCM of denominators of coefficients of a polynomial\n *\/\n\n\/\/ Compute LCM of denominators of coefficients by going through the\n\/\/ expression recursively (used internally by lcm_of_coefficients_denominators())\nstatic numeric lcmcoeff(const ex &e, const numeric &l)\n{\n\tif (is_exactly_a(e)\n and e.info(info_flags::rational))\n\t\treturn lcm(ex_to(e).denom(), l);\n\tif (is_exactly_a(e)) {\n\t\tnumeric c = *_num1_p;\n\t\tfor (size_t i=0; i(e)) {\n\t\tnumeric c = *_num1_p;\n\t\tfor (size_t i=0; i(e)) {\n\t\tif (is_exactly_a(e.op(0)))\n\t\t\treturn l;\n\n ex t = pow(lcmcoeff(e.op(0), l), ex_to(e.op(1)));\n if (is_exactly_a(t))\n return ex_to(t);\n\t}\n\treturn l;\n}\n\n\/** Compute LCM of denominators of coefficients of a polynomial.\n * Given a polynomial with rational coefficients, this function computes\n * the LCM of the denominators of all coefficients. This can be used\n * to bring a polynomial from Q[X] to Z[X].\n *\n * @param e multivariate polynomial (need not be expanded)\n * @return LCM of denominators of coefficients *\/\nnumeric lcm_of_coefficients_denominators(const ex &e)\n{\n\treturn lcmcoeff(e, *_num1_p);\n}\n\n\/** Bring polynomial from Q[X] to Z[X] by multiplying in the previously\n * determined LCM of the coefficient's denominators.\n *\n * @param e multivariate polynomial (need not be expanded)\n * @param lcm LCM to multiply in *\/\nex multiply_lcm(const ex &e, const numeric &lcm)\n{\n\tif (is_exactly_a(e)) {\n\t\tsize_t num = e.nops();\n\t\texvector v; v.reserve(num + 1);\n\t\tnumeric lcm_accum = *_num1_p;\n\t\tfor (size_t i=0; isetflag(status_flags::dynallocated);\n\t}\n if (is_exactly_a(e)) {\n\t\tsize_t num = e.nops();\n\t\texvector v; v.reserve(num);\n\t\tfor (size_t i=0; isetflag(status_flags::dynallocated);\n\t}\n if (is_exactly_a(e)) {\n\t\tif (is_exactly_a(e.op(0)))\n\t\t\treturn e * lcm;\n if (not is_exactly_a(e.op(1)))\n return e * lcm;\n ex t = lcm.power(ex_to(e.op(1)).inverse());\n if (not is_exactly_a(t))\n return e * lcm;\n const numeric& root_of_lcm = ex_to(t);\n if (root_of_lcm.is_rational())\n return pow(multiply_lcm(e.op(0), root_of_lcm), e.op(1));\n\t}\n return e * lcm;\n}\n\n\/*\n * Separation of unit part, content part and primitive part of polynomials\n *\/\n\n\/** Compute unit part (= sign of leading coefficient) of a multivariate\n * polynomial in Q[x]. The product of unit part, content part, and primitive\n * part is the polynomial itself.\n *\n * @param x main variable\n * @return unit part\n * @see ex::content, ex::primpart, ex::unitcontprim *\/\nex ex::unit(const ex &x) const\n{\n\tex c = expand().lcoeff(x);\n\tif (is_exactly_a(c))\n\t\treturn c.info(info_flags::negative) ?_ex_1 : _ex1;\n\n ex y;\n if (c.get_first_symbol(y))\n return c.unit(y);\n\n throw(std::invalid_argument(\"invalid expression in unit()\"));\n}\n\n\n\/** Compute content part (= unit normal GCD of all coefficients) of a\n * multivariate polynomial in Q[x]. The product of unit part, content part,\n * and primitive part is the polynomial itself.\n *\n * @param x main variable\n * @return content part\n * @see ex::unit, ex::primpart, ex::unitcontprim *\/\nex ex::content(const ex &x) const\n{\n\tif (is_exactly_a(*this))\n\t\treturn info(info_flags::negative) ? -*this : *this;\n\n\tif (this->is_zero())\n\t\treturn _ex0;\n\n\tex u, c, p;\n\tunitcontprim(x, u, c, p);\n\treturn c;\n}\n\n\n\/** Compute primitive part of a multivariate polynomial in Q[x]. The result\n * will be a unit-normal polynomial with a content part of 1. The product\n * of unit part, content part, and primitive part is the polynomial itself.\n *\n * @param x main variable\n * @return primitive part\n * @see ex::unit, ex::content, ex::unitcontprim *\/\nex ex::primpart(const ex &x) const\n{\n\t\/\/ We need to compute the unit and content anyway, so call unitcontprim()\n\tex u, c, p;\n\tunitcontprim(x, u, c, p);\n\treturn p;\n}\n\n\n\/** Compute primitive part of a multivariate polynomial in Q[x] when the\n * content part is already known. This function is faster in computing the\n * primitive part than the previous function.\n *\n * @param x main variable\n * @param c previously computed content part\n * @return primitive part *\/\nex ex::primpart(const ex &x, const ex &c) const\n{\n\tif (is_zero() || c.is_zero())\n\t\treturn _ex0;\n\tif (is_exactly_a(*this))\n\t\treturn _ex1;\n\n\t\/\/ Divide by unit and content to get primitive part\n\tex u = unit(x);\n\tif (is_exactly_a(c))\n\t\treturn *this \/ (c * u);\n\treturn quo(*this, c * u, x, false);\n}\n\n\n\/** Compute unit part, content part, and primitive part of a multivariate\n * polynomial in Q[x]. The product of the three parts is the polynomial\n * itself.\n *\n * @param x main variable\n * @param u unit part (returned)\n * @param c content part (returned)\n * @param p primitive part (returned)\n * @see ex::unit, ex::content, ex::primpart *\/\nvoid ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const\n{\n\t\/\/ Quick check for zero (avoid expanding)\n\tif (is_zero()) {\n\t\tu = _ex1;\n\t\tc = p = _ex0;\n\t\treturn;\n\t}\n\n\t\/\/ Special case: input is a number\n\tif (is_exactly_a(*this)) {\n\t\tif (info(info_flags::negative)) {\n\t\t\tu = _ex_1;\n\t\t\tc = abs(ex_to(*this));\n\t\t} else {\n\t\t\tu = _ex1;\n\t\t\tc = *this;\n\t\t}\n\t\tp = _ex1;\n\t\treturn;\n\t}\n\n\t\/\/ Compute unit and content\n\tu = unit(x);\n\n expairvec vec;\n coefficients(x, vec);\n c = vec[0].first;\n for (const auto& pair : range(vec.begin()+1, vec.end())) {\n c = gcdpoly(c, pair.first, nullptr, nullptr, false);\n }\n\n p = _ex0;\n if (is_exactly_a(c))\n for (const auto& pair : vec)\n p += (pair.first \/ (c * u)) * pow(x, pair.second);\n else\n for (const auto& pair : vec)\n p += quo(pair.first, c * u, x, false) * pow(x, pair.second);\n}\n\nex resultant(const ex & e1, const ex & e2, const ex & s)\n{\n\tconst ex ee1 = e1.expand();\n\tconst ex ee2 = e2.expand();\n\tif (!ee1.info(info_flags::polynomial) ||\n\t !ee2.info(info_flags::polynomial)) {\n ex res, f1, f2;\n bool changed = factor(ee1, res);\n if (changed)\n f1 = res;\n else\n f1 = ee1;\n changed = factor(ee2, res);\n if (changed)\n f2 = res;\n else\n f2 = ee1;\n ex den1 = f1.denom();\n ex den2 = f2.denom();\n if (not den1.is_one() and den1.is_equal(den2))\n return resultant(f1.numer(), f2.numer(), s);\n\t\tthrow(std::runtime_error(\"resultant(): arguments must be polynomials\"));\n }\n\n return resultantpoly(ee1, ee2, s);\n}\n\n} \/\/ namespace GiNaC\n\n","avg_line_length":30.0553633218,"max_line_length":84,"alphanum_fraction":0.6158185586} {"size":2092,"ext":"cpp","lang":"C++","max_stars_count":13.0,"content":"\/\/ Copyright (c) 2005 - 2015 Marc de Kamps\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n\/\/ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n#define BOOST_TEST_DYN_LINK\n#include \n#include \n#include \n#include \n\n\nBOOST_AUTO_TEST_CASE(MeshAlgorithmTest){\n\n\tstd::string model_name = \"life21da341-bd4a-4077-93c2-4d11804d0882.model\";\n\tstd::vector mat_names;\n\tmat_names.push_back(\"life21da341-bd4a-4077-93c2-4d11804d0882_0.03_0_0_0_.mat\");\n\n\n\tdouble h = 1e-4;\n\tTwoDLib::MeshAlgorithm\n\t\talg\n\t\t(\n\t\t\tmodel_name,\n\t\t\tstd::vector{mat_names},\n\t\t\th\n\t\t);\n}\n\n\n","avg_line_length":48.6511627907,"max_line_length":162,"alphanum_fraction":0.7743785851} {"size":2068,"ext":"hxx","lang":"C++","max_stars_count":154.0,"content":"\n\/\/ AUTO GENERATED by vnxcppcodegen\n\n#ifndef INCLUDE_mmx_BlockHeader_validate_return_HXX_\n#define INCLUDE_mmx_BlockHeader_validate_return_HXX_\n\n#include \n#include \n\n\nnamespace mmx {\n\nclass MMX_EXPORT BlockHeader_validate_return : public ::vnx::Value {\npublic:\n\t\n\t\n\ttypedef ::vnx::Value Super;\n\t\n\tstatic const vnx::Hash64 VNX_TYPE_HASH;\n\tstatic const vnx::Hash64 VNX_CODE_HASH;\n\t\n\tstatic constexpr uint64_t VNX_TYPE_ID = 0x37ed485c972b21dull;\n\t\n\tBlockHeader_validate_return() {}\n\t\n\tvnx::Hash64 get_type_hash() const override;\n\tstd::string get_type_name() const override;\n\tconst vnx::TypeCode* get_type_code() const override;\n\t\n\tstatic std::shared_ptr create();\n\tstd::shared_ptr clone() const override;\n\t\n\tvoid read(vnx::TypeInput& _in, const vnx::TypeCode* _type_code, const uint16_t* _code) override;\n\tvoid write(vnx::TypeOutput& _out, const vnx::TypeCode* _type_code, const uint16_t* _code) const override;\n\t\n\tvoid read(std::istream& _in) override;\n\tvoid write(std::ostream& _out) const override;\n\t\n\ttemplate\n\tvoid accept_generic(T& _visitor) const;\n\tvoid accept(vnx::Visitor& _visitor) const override;\n\t\n\tvnx::Object to_object() const override;\n\tvoid from_object(const vnx::Object& object) override;\n\t\n\tvnx::Variant get_field(const std::string& name) const override;\n\tvoid set_field(const std::string& name, const vnx::Variant& value) override;\n\t\n\tfriend std::ostream& operator<<(std::ostream& _out, const BlockHeader_validate_return& _value);\n\tfriend std::istream& operator>>(std::istream& _in, BlockHeader_validate_return& _value);\n\t\n\tstatic const vnx::TypeCode* static_get_type_code();\n\tstatic std::shared_ptr static_create_type_code();\n\t\n};\n\ntemplate\nvoid BlockHeader_validate_return::accept_generic(T& _visitor) const {\n\t_visitor.template type_begin(0);\n\t_visitor.template type_end(0);\n}\n\n\n} \/\/ namespace mmx\n\n\nnamespace vnx {\n\n} \/\/ vnx\n\n#endif \/\/ INCLUDE_mmx_BlockHeader_validate_return_HXX_\n","avg_line_length":28.7222222222,"max_line_length":106,"alphanum_fraction":0.7751450677} {"size":70475,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"\/**\n * Copyright (C) 2016-2017 Xilinx, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n * not use this file except in compliance with the License. A copy of the\n * License is located at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/**\n * This file contains the implementation of the application debug\n * It exposes a set of functions that are callable from debugger(GDB)\n * It defines data structures that provide the view of runtime data structures such as cl_event and cl_meme\n * It defines lambda functions that are attached as debug action with the cl_event\n *\/\n#include \"appdebug.h\"\n#include \"appdebug_track.h\"\n#include \"xdp\/rt_singleton.h\"\n#include \"xdp\/profile\/core\/rt_profile.h\"\n\n#include \"xocl\/core\/event.h\"\n#include \"xocl\/core\/command_queue.h\"\n#include \"xocl\/core\/device.h\"\n#include \"xocl\/core\/platform.h\"\n#include \"xocl\/core\/context.h\"\n#include \"xocl\/core\/compute_unit.h\"\n#include \"xocl\/core\/execution_context.h\"\n\n#include \"xclbin\/binary.h\"\n\n#include \"xclperf.h\"\n#include \"xcl_app_debug.h\"\n#include \"xclbin.h\"\n#include \"xcl_axi_checker_codes.h\"\n\n#include \n#include \n#include \n#include \"xocl\/api\/plugin\/xdp\/appdebug.h\"\n\nnamespace {\nstatic const int debug_ip_layout_max_size = 65536;\n\nconst char*\nevent_commandtype_to_string(cl_command_type cmd)\n{\n if (cmd < CL_COMMAND_NDRANGE_KERNEL || cmd > CL_COMMAND_FILL_IMAGE) {\n return \"Bad command\";\n }\n static const char* tbl [] = {\"CL_COMMAND_NDRANGE_KERNEL\", \"CL_COMMAND_TASK\", \"CL_COMMAND_NATIVE_KERNEL\", \"CL_COMMAND_READ_BUFFER\", \"CL_COMMAND_WRITE_BUFFER\",\n \"CL_COMMAND_COPY_BUFFER\", \"CL_COMMAND_READ_IMAGE\", \"CL_COMMAND_WRITE_IMAGE\", \"CL_COMMAND_COPY_IMAGE\", \"CL_COMMAND_COPY_IMAGE_TO_BUFFER\",\n \"CL_COMMAND_COPY_BUFFER_TO_IMAGE\", \"CL_COMMAND_MAP_BUFFER\", \"CL_COMMAND_MAP_IMAGE\", \"CL_COMMAND_UNMAP_MEM_OBJECT\", \"CL_COMMAND_MARKER\",\n \"CL_COMMAND_ACQUIRE_GL_OBJECTS\", \"CL_COMMAND_RELEASE_GL_OBJECTS\", \"CL_COMMAND_READ_BUFFER_RECT\", \"CL_COMMAND_WRITE_BUFFER_RECT\", \"CL_COMMAND_COPY_BUFFER_RECT\",\n \"CL_COMMAND_USER\", \"CL_COMMAND_BARRIER\", \"CL_COMMAND_MIGRATE_MEM_OBJECTS\", \"CL_COMMAND_FILL_BUFFER\", \"CL_COMMAND_FILL_IMAGE\"};\n return tbl[cmd-CL_COMMAND_NDRANGE_KERNEL];\n}\nconst char*\nevent_commandstatus_to_string(cl_int status)\n{\n if (status == -1) return \"Locked\";\n if (status > 3 || status < 0)return \"Unknown\";\n static const char* tbl[] = {\"Complete\", \"Running\",\"Submitted\",\"Queued\"};\n return tbl[status];\n}\n\n\/\/Iterate all events and find all events that aEvent depends on, returns a vector\n\/\/Note that, this function calls try_get_chain() which locks the event object\n\/\/So any functions called while iterating on the chain should not lock the event\n\/\/Also, note that app_debug_track->for_each locks the tracker data structure,\n\/\/so the lambda cannot call any functions that would inturn try to lock tracker\nstd::vector event_chain_to_dependencies (xocl::event* aEvent) {\n std::vector dependencies;\n\n auto findDependencies = [aEvent, &dependencies] (cl_event aEv) {\n xocl::event * e = xocl::xocl(aEv);\n \/\/consider all events, including user events that are not in any command queue\n xocl::range_lock&& aRange = e->try_get_chain();\n for (auto it = aRange.begin(); it!=aRange.end(); ++it) {\n if (*it == aEvent) {\n \/\/Add ev to the aEvent dependent list\n dependencies.push_back(e);\n break;\n }\n }\n };\n\n appdebug::app_debug_track::getInstance()->for_each(findDependencies);\n return dependencies;\n}\n\nstd::string event_dependencies_to_string(std::vector&& dependencies ) {\n std::stringstream sstr;\n if (!dependencies.size())\n return \"None\";\n for(auto it = dependencies.begin(); it!=dependencies.end(); ++it) {\n xocl::event* e = *it;\n std::string status_str;\n try {\n status_str = event_commandstatus_to_string(e->try_get_status());\n }\n catch (const xocl::error & ex) {\n status_str = \"Not Available\";\n }\n sstr << \"[\" << std::hex << (cl_event)e << \", \" << std::dec << e->get_uid() << \", \" << status_str << \", \" <<\n event_commandtype_to_string (e->get_command_type()) << \"]\";\n }\n return sstr.str();\n}\n\n} \/\/ namespace\n\nnamespace appdebug {\n\n\/\/ Call back function to be called when a command is sent to the scheduler\nvoid cb_scheduler_cmd_start (const xrt::command* aCommand, const xocl::execution_context* aContext)\n{\n \/\/update the datastructure associated with the given event\n try {\n app_debug_track::event_data_t& edt = app_debug_track::getInstance()->get_data(static_cast(const_cast(aContext->get_event())));\n edt.m_start = true;\n }\n catch (const xocl::error & ex) {\n \/\/INVALID_OBJECT is the only expected exception, anything else rethrow\n if(ex.get_code() != DBG_EXCEPT_INVALID_OBJECT) {\n throw;\n }\n }\n}\n\n\n\n\/\/ Call back function to be called when a command is finished\nvoid cb_scheduler_cmd_done (const xrt::command* aCommand, const xocl::execution_context* aContext)\n{\n \/\/update the datastructure associated with the given event\n try {\n app_debug_track::event_data_t& edt = app_debug_track::getInstance()->get_data(static_cast(const_cast(aContext->get_event())));\n ++edt.m_ncomplete;\n }\n catch (const xocl::error & ex) {\n \/\/INVALID_OBJECT is the only expected exception, anything else rethrow\n if(ex.get_code() != DBG_EXCEPT_INVALID_OBJECT) {\n throw;\n }\n }\n}\n\nbool app_debug_view_base::isInValid() const\n{\n return m_invalid;\n}\n\nstd::string app_debug_view_base::geterrmsg() const\n{\n return m_msg;\n\n}\n\ntemplate\nT* app_debug_view :: getdata() const\n{\n return m_data;\n}\n\/*\n * create explicit instantiation of template classes\n * This is needed as there are no other instantiation\n * created in the code and for gdb to call these\n * we need template instantiation of these\n *\/\ntemplate class app_debug_view>;\ntemplate class app_debug_view>;\ntemplate class app_debug_view;\ntemplate class app_debug_view;\ntemplate class app_debug_view>;\ntemplate class app_debug_view;\ntemplate class app_debug_view;\ntemplate class app_debug_view;\ntemplate class app_debug_view;\ntemplate class app_debug_view>;\ntemplate class app_debug_view>;\n\ntemplate class app_debug_track;\ntemplate class app_debug_track;\n\n\/\/Initialize the static member of app_debug_track\ntemplate<> bool app_debug_track::m_set = true;\ntemplate<> bool app_debug_track::m_set = true;\nbool app_debug_track::m_set = true;\n\n\nstd::string event_debug_view_base::getstring(int aVerbose, int aQuotes)\n{\n std::stringstream sstr;\n std::string quotes;\n if (aQuotes) quotes = \"\\\"\";\n else quotes = \"\";\n\n \/\/for the xpe commands show more info about commands\n if (aVerbose) {\n if (m_event) {\n sstr << quotes << \"Event\" << quotes << \" : \" << quotes << std::hex << m_event << quotes << \", \";\n if (xocl::xocl(m_event)->get_command_queue()) {\n sstr << quotes << \"Queue\" << quotes << \" : \" << quotes << std::hex << xocl::xocl(m_event)->get_command_queue() << quotes << \", \";\n if (xocl::xocl(m_event)->get_command_queue()->get_device()) {\n sstr << quotes << \"Device\" << quotes << \" : \" << quotes << xocl::xocl(m_event)->get_command_queue()->get_device()->get_name() << quotes << \", \";\n }\n }\n else {\n sstr << quotes << \"Queue\" << quotes << \" : \" << quotes << \"None\" << quotes << \", \";\n }\n }\n }\n if (aQuotes) {\n \/\/For gui dbg perspective we want to show event pointers\n sstr << quotes << \"name\" << quotes << \" : \" << quotes << \"Event-\" << std::hex << m_event << quotes << \", \";\n }\n sstr << quotes << \"Uid\" << quotes << \" : \" << quotes << std::dec << m_uid << quotes << \", \";\n sstr << quotes << \"Status\" << quotes << \" : \" << quotes << m_status_name << quotes << \", \";\n sstr << quotes << \"Type\" << quotes << \" : \" << quotes << m_command_name << quotes << \", \";\n sstr << quotes << \"WaitingOn\" << quotes << \" : \" << quotes << m_wait_list << quotes ;\n return sstr.str();\n}\n\nstd::string event_debug_view_readwrite::getstring(int aVerbose, int aQuotes)\n{\n std::stringstream sstr;\n std::string quotes;\n if (aQuotes) quotes = \"\\\"\";\n else quotes = \"\";\n\n sstr << event_debug_view_base::getstring(aVerbose, aQuotes) << \", \";\n sstr << quotes << \"Description\" << quotes << \" : \";\n sstr << quotes;\n sstr << \"Transfer \" << m_size << \" bytes \" << ((m_cmd == CL_COMMAND_READ_BUFFER)? \"from \" : \"to \");\n sstr << \"cl_mem \" << std::hex << m_buffer << \"+\" << std::dec << m_offset;\n sstr << quotes;\n return sstr.str();\n}\nstd::string event_debug_view_copy::getstring(int aVerbose, int aQuotes)\n{\n std::stringstream sstr;\n std::string quotes;\n if (aQuotes) quotes = \"\\\"\";\n else quotes = \"\";\n\n sstr << event_debug_view_base::getstring(aVerbose, aQuotes) << \", \";\n sstr << quotes << \"Description\" << quotes << \" : \";\n sstr << quotes;\n sstr << \"Copy from \";\n sstr << \"cl_mem \" << std::hex << m_src_buffer << \"+\" << std::dec << m_src_offset;\n sstr << \" to \";\n sstr << \" cl_mem \" << std::hex << m_dst_buffer << \"+\" << std::dec << m_dst_offset;\n sstr << quotes;\n return sstr.str();\n}\nstd::string event_debug_view_fill::getstring(int aVerbose, int aQuotes)\n{\n std::stringstream sstr;\n std::string quotes;\n if (aQuotes) quotes = \"\\\"\";\n else quotes = \"\";\n sstr << event_debug_view_base::getstring(aVerbose, aQuotes) << \", \";\n sstr << quotes << \"Description\" << quotes << \" : \";\n sstr << quotes;\n sstr << \"Fill \" << m_size << \" bytes into\";\n sstr << \" cl_mem \" << std::hex << m_buffer << \"+\" << std::dec << m_offset;\n sstr << \" with \" << m_pattern_size << \" bytes of \" << std::hex << m_pattern ;\n sstr << quotes;\n return sstr.str();\n}\nstd::string event_debug_view_map::getstring(int aVerbose, int aQuotes)\n{\n std::stringstream sstr;\n std::string quotes;\n if (aQuotes) quotes = \"\\\"\";\n else quotes = \"\";\n\n sstr << event_debug_view_base::getstring(aVerbose, aQuotes) << \", \";\n sstr << quotes << \"Description\" << quotes << \" : \";\n sstr << quotes;\n sstr << \"Map cl_mem \" << std::hex << m_buffer << \" with flags \" << \"0x\" << std::hex << m_flags;\n sstr << quotes;\n return sstr.str();\n}\nstd::string event_debug_view_migrate::getstring(int aVerbose, int aQuotes)\n{\n std::stringstream sstr;\n std::string quotes;\n if (aQuotes) quotes = \"\\\"\";\n else quotes = \"\";\n\n sstr << event_debug_view_base::getstring(aVerbose, aQuotes) << \", \";\n sstr << quotes << \"Description\" << quotes << \" : \";\n sstr << quotes;\n if (m_kernel_args_migrate) {\n sstr << \"Migrate kernel args for \" << m_kname;\n }\n else {\n sstr << \"Migrate \" << m_num_objects << \" cl_mem objects \";\n for(unsigned int i = 0; iget_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n buffer,\n offset,\n size,\n ptr\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_copybuf(xocl::event* event, cl_mem src_buffer, cl_mem dst_buffer, size_t src_offset, size_t dst_offset, size_t size)\n{\n event_debug_view_copy *edv = new event_debug_view_copy (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n src_buffer,\n src_offset,\n dst_buffer,\n dst_offset,\n size\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_fill_buffer (xocl::event* event, cl_mem buffer, const void* pattern, size_t pattern_size, size_t offset, size_t size)\n{\n event_debug_view_fill *edv = new event_debug_view_fill (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n buffer,\n offset,\n pattern,\n pattern_size,\n size\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_map (xocl::event* event, cl_mem buffer,cl_map_flags map_flag)\n{\n event_debug_view_map *edv = new event_debug_view_map (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n buffer,\n map_flag\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_migrate (xocl::event* event, cl_uint num_mem_objects, const cl_mem *mem_objects, cl_mem_migration_flags flags)\n{\n event_debug_view_migrate *edv = new event_debug_view_migrate (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n mem_objects,\n num_mem_objects,\n flags\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_ndrange_migrate (xocl::event* event, cl_kernel kernel)\n{\n std::string kname = xocl::xocl(kernel)->get_name();\n\n event_debug_view_migrate *edv = new event_debug_view_migrate (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n kname\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_ndrange (xocl::event* event, cl_kernel kernel)\n{\n \/\/get cuname and workgroup information\n size_t nworkgroups = 0;\n bool issubmitted = false;\n cl_int evstatus = event->try_get_status();\n\n std::string kname = xocl::xocl(kernel)->get_name();\n\n if (evstatus == CL_SUBMITTED || evstatus == CL_RUNNING) {\n auto exctx = event->get_execution_context();\n nworkgroups = exctx->get_num_work_groups();\n issubmitted = true;\n }\n uint32_t ncomplete = app_debug_track::getInstance()->try_get_data(event).m_ncomplete;\n bool has_started = app_debug_track::getInstance()->try_get_data(event).m_start;\n if (evstatus == CL_COMPLETE) {\n \/\/There could be completed lingering events in the system, so need to handle completed events\n nworkgroups = ncomplete;\n issubmitted = true;\n }\n event_debug_view_ndrange *edv = new event_debug_view_ndrange (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n (evstatus == CL_COMPLETE) ? \"Complete\" : (has_started ? \"Scheduled\" : \"Waiting\"),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n kname,\n nworkgroups,\n ncomplete,\n issubmitted\n );\n global_return_edv = edv;\n}\n\nvoid cb_action_unmap (xocl::event* event, cl_mem buffer)\n{\n event_debug_view_unmap *edv = new event_debug_view_unmap (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n buffer\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_barrier_marker(xocl::event* event)\n{\n event_debug_view_barrier_marker *edv = new event_debug_view_barrier_marker (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event))\n );\n global_return_edv = edv;\n}\n\nvoid\ncb_action_readwrite_image (xocl::event* event, cl_mem image,const size_t* origin,const size_t* region, size_t row_pitch,size_t slice_pitch,const void* ptr)\n{\n event_debug_view_readwrite_image *edv = new event_debug_view_readwrite_image (\n (cl_event)event,\n event->get_uid(),\n event->get_command_type(),\n event_commandtype_to_string (event->get_command_type()),\n event_commandstatus_to_string (event->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (event)),\n image,\n std::vector(origin, origin+3),\n std::vector(region, region+3),\n row_pitch,\n slice_pitch,\n ptr\n );\n global_return_edv = edv;\n}\n\nvoid register_xocl_appdebug_callbacks() {\n \/* event *\/\n xocl::event::register_constructor_callbacks(appdebug::add_event);\n xocl::event::register_destructor_callbacks(appdebug::remove_event);\n \/* command queue *\/\n xocl::command_queue::register_constructor_callbacks(appdebug::add_command_queue);\n xocl::command_queue::register_destructor_callbacks(appdebug::remove_command_queue);\n\n \/*cl_mem*\/\n xocl::memory::register_constructor_callbacks(appdebug::add_clmem);\n xocl::memory::register_destructor_callbacks(appdebug::remove_clmem);\n\n \/*opencl api*\/\n xocl::appdebug::register_cb_action_readwrite (cb_action_readwrite);\n xocl::appdebug::register_cb_action_copybuf (cb_action_copybuf);\n xocl::appdebug::register_cb_action_fill_buffer (cb_action_fill_buffer);\n xocl::appdebug::register_cb_action_map (cb_action_map);\n xocl::appdebug::register_cb_action_migrate (cb_action_migrate);\n xocl::appdebug::register_cb_action_ndrange_migrate (cb_action_ndrange_migrate);\n xocl::appdebug::register_cb_action_ndrange (cb_action_ndrange);\n xocl::appdebug::register_cb_action_unmap (cb_action_unmap);\n xocl::appdebug::register_cb_action_barrier_marker (cb_action_barrier_marker);\n xocl::appdebug::register_cb_action_readwrite_image (cb_action_readwrite_image);\n}\n\ninline\nvoid try_get_queue_sizes (cl_command_queue cq, size_t& nQueued, size_t& nSubmitted) {\n \/\/Assumes that cq is validated\n\n \/\/The lambda cannot call any functions that will lock tracker, as the lock\n \/\/is already claimed by for_each\n auto fLambdaCounter = [cq, &nQueued, &nSubmitted] (cl_event aEvent) {\n if (xocl::xocl(aEvent)->get_command_queue() == cq) {\n if (xocl::xocl(aEvent)->try_get_status() == CL_QUEUED)\n ++nQueued;\n else\n ++nSubmitted;\n }\n };\n \/\/Iterate all events that are in cq and count based on their status (queued\/submitted)\n nQueued = 0; nSubmitted = 0;\n app_debug_track::getInstance()->for_each(std::move(fLambdaCounter));\n}\n\n\/\/Debug functions called from GDB\napp_debug_view>*\nclPrintCmdQOccupancy(cl_command_queue cq)\n{\n std::pair *size_pair = new std::pair (SIZE_MAX, SIZE_MAX);\n auto adv = new app_debug_view> (size_pair, [size_pair](){delete size_pair;});\n try {\n validate_command_queue(cq);\n }\n catch (const xocl::error &ex) {\n adv->setInvalidMsg(true, ex.what());\n return adv;\n }\n\n try {\n try_get_queue_sizes(cq, size_pair->first, size_pair->second);\n }\n catch (const xocl::error & ex) {\n adv->setInvalidMsg(true, ex.what());\n }\n return adv;\n}\n\napp_debug_view >*\nclPrintCmdQQueued(cl_command_queue cq)\n{\n size_t nq, ns;\n try {\n validate_command_queue(cq);\n }\n catch (const xocl::error &ex) {\n auto adv = new app_debug_view > (nullptr, nullptr, true, ex.what());\n return adv;\n }\n\n try {\n try_get_queue_sizes(cq, nq, ns);\n }\n catch (const xocl::error& ex) {\n auto adv = new app_debug_view > (nullptr, nullptr, true, ex.what());\n return adv;\n }\n\n std::vector *v = new std::vector();\n\n std::vector selectedEventsVec;\n\n auto collect_events_lamda = [cq, &selectedEventsVec] (cl_event aEvent) {\n xocl::event *e = xocl::xocl(aEvent);\n if (e->get_command_queue() == cq && e->try_get_status() == CL_QUEUED)\n selectedEventsVec.push_back(e);\n };\n\n auto add_edv_lambda = [v](xocl::event *e) {\n v->push_back((e->trigger_debug_action(), global_return_edv));\n };\n\n auto delete_edv_lambda = [v]() {\n for (auto edv : *v)\n delete edv;\n delete v;\n };\n auto adv = new app_debug_view > (v, std::move(delete_edv_lambda));\n\n try {\n \/\/First collect the events of interest in a vector and then call debug actions on them\n \/\/for_each and debug action both need the lock on the tracker resulting in deadlock.\n app_debug_track::getInstance()->for_each(std::move(collect_events_lamda));\n\n std::for_each(selectedEventsVec.begin(), selectedEventsVec.end(), std::move(add_edv_lambda));\n }\n catch(const xocl::error& ex) {\n adv->setInvalidMsg(true, ex.what());\n }\n return adv;\n}\n\napp_debug_view >*\nclPrintCmdQSubmitted(cl_command_queue cq)\n{\n size_t nq, ns;\n try {\n validate_command_queue(cq);\n }\n catch (const xocl::error& ex) {\n auto adv = new app_debug_view > (nullptr, nullptr, true, ex.what());\n return adv;\n }\n\n try {\n try_get_queue_sizes(cq, nq, ns);\n }\n catch (const xocl::error& ex) {\n auto adv = new app_debug_view > (nullptr, nullptr, true, ex.what());\n return adv;\n }\n std::vector *v = new std::vector();\n std::vector selectedEventsVec;\n\n auto collect_events_lamda = [cq, &selectedEventsVec] (cl_event aEvent) {\n xocl::event* e = xocl::xocl(aEvent);\n if (e->get_command_queue() == cq && e->try_get_status() != CL_QUEUED)\n selectedEventsVec.push_back(e);\n };\n\n auto add_edv_lambda = [v](xocl::event *e) {\n v->push_back((e->trigger_debug_action(), global_return_edv));\n };\n\n auto delete_edv_lambda = [v]() {\n for (auto edv : *v)\n delete edv;\n delete v;\n };\n auto adv = new app_debug_view > (v, std::move(delete_edv_lambda));\n\n try {\n \/\/First collect the events of interest in a vector and then call debug actions on them\n \/\/for_each and debug action both need the lock on the tracker resulting in deadlock.\n app_debug_track::getInstance()->for_each(std::move(collect_events_lamda));\n std::for_each(selectedEventsVec.begin(), selectedEventsVec.end(), std::move(add_edv_lambda));\n }\n catch(const xocl::error& ex) {\n adv->setInvalidMsg(true, ex.what());\n }\n return adv;\n}\nvoid\nclFreeAppDebugView(app_debug_view_base* aView)\n{\n if (!aView) return;\n delete aView;\n}\n\napp_debug_view *\nclGetMemInfo(cl_mem aMem) {\n uint64_t addr;\n std::string bank;\n clmem_debug_view *mdv;\n\n try {\n validate_clmem(aMem);\n }\n catch (const xocl::error& ex) {\n auto adv = new app_debug_view (nullptr, nullptr, true, ex.what());\n return adv;\n }\n\n auto xoclMem = xocl::xocl(aMem);\n try {\n xoclMem->try_get_address_bank(addr, bank);\n mdv = new clmem_debug_view(aMem, xoclMem->get_uid(), bank, addr,\n xoclMem->get_size(), xoclMem->get_host_ptr());\n }\n catch (const xocl::error& ex) {\n \/\/locked, cannot provide addr\/bank information\n\n mdv = new clmem_debug_view(aMem, xoclMem->get_uid(), \"Unknown\", -1,\n xoclMem->get_size(), xoclMem->get_host_ptr());\n\n auto adv = new app_debug_view (mdv, [mdv] () {delete mdv;}, true, ex.what());\n return adv;\n }\n auto adv = new app_debug_view (mdv, [mdv] () {delete mdv;}, false, \"\");\n return adv;\n}\n\napp_debug_view*\nclGetEventInfo(cl_event aEvent) {\n event_debug_view_base* edv;\n \/\/aEvent could be an event that doesn't have trigger_debug_action set\n \/\/When trigger_debug_action the exception is caught check if app_\n try {\n validate_event(aEvent);\n }\n catch (const xocl::error &ex) {\n auto adv = new app_debug_view (nullptr, nullptr, true, ex.what());\n return adv;\n }\n auto xoclEvent = xocl::xocl(aEvent);\n try {\n edv = (xoclEvent->trigger_debug_action(), global_return_edv);\n }\n catch (const xocl::error & ex) {\n if (ex.get() == DBG_EXCEPT_NO_DBG_ACTION) {\n \/\/if no debug action set then return basic information\n edv = new event_debug_view_base (aEvent,\n xoclEvent->get_uid(),\n xoclEvent->get_command_type(),\n event_commandtype_to_string (xoclEvent->get_command_type()),\n event_commandstatus_to_string (xoclEvent->try_get_status()),\n event_dependencies_to_string(event_chain_to_dependencies (xoclEvent)));\n }\n else {\n \/\/some other exception\n auto adv = new app_debug_view (nullptr, nullptr, true, ex.what());\n return adv;\n }\n }\n auto adv = new app_debug_view (edv, [edv] () {delete edv;}, false, \"\");\n return adv;\n}\n\napp_debug_view>*\nclGetCmdQueues()\n{\n std::vector *v = new std::vector();\n auto adv = new app_debug_view> (v, [v](){delete v;});\n try {\n app_debug_track::getInstance()->for_each([v](cl_command_queue aQueue) {v->push_back(aQueue);});\n }\n catch (const xocl::error &ex) {\n adv->setInvalidMsg(true, ex.what());\n return adv;\n }\n return adv;\n}\n\napp_debug_view>*\nclGetClMems()\n{\n std::vector *v = new std::vector();\n auto adv = new app_debug_view> (v, [v](){delete v;});\n try {\n app_debug_track::getInstance()->for_each([v](cl_mem aMem) {v->push_back(aMem);});\n }\n catch (const xocl::error &ex) {\n adv->setInvalidMsg(true, ex.what());\n return adv;\n }\n\n return adv;\n}\n\nstatic\nstd::string\ngetArgValueString(const xocl::event* aEvent)\n{\n std::stringstream sstr;\n auto ctx = aEvent->get_execution_context();\n for (auto& arg : ctx->get_indexed_argument_range()) {\n auto address_space = arg->get_address_space();\n if (address_space == xocl::kernel::argument::addr_space_type::SPIR_ADDRSPACE_PRIVATE)\n {\n \/\/auto arginforange = arg->get_arginfo_range();\n \/\/sstr << arg->get_name() << \" = \" << getscalarval((const void*)arg->get_value(), arg->get_size(),arginforange) << \" \";\n sstr << arg->get_name() << \" = \" << arg->get_string_value() << \" \";\n } else if (address_space == xocl::kernel::argument::addr_space_type::SPIR_ADDRSPACE_PIPES) {\n sstr << arg->get_name() << \" = \" << \"stream arg \" << std::dec;\n\n } else if (address_space == xocl::kernel::argument::addr_space_type::SPIR_ADDRSPACE_GLOBAL\n || address_space == xocl::kernel::argument::addr_space_type::SPIR_ADDRSPACE_CONSTANT)\n {\n uint64_t physaddr = 0;\n std::string bank = \"\";\n if (auto mem = arg->get_memory_object()) {\n xocl::xocl(mem)->try_get_address_bank(physaddr, bank);\n }\n\n sstr << arg->get_name() << \" = 0x\" << std::hex << physaddr << std::dec << \"(Bank-\";\n sstr << bank;\n sstr << \") \";\n }\n else if (address_space == xocl::kernel::argument::addr_space_type::SPIR_ADDRSPACE_LOCAL)\n {\n sstr << arg->get_name() << \" = \" << \"local arg \" << std::dec;\n }\n }\n\n \/\/Now collect the progvars\n size_t eventargitint = 0;\n\n for (auto& arg : ctx->get_progvar_argument_range()) {\n uint64_t physaddr = 0;\n std::string bank;\n if (eventargitint == 0) sstr << \"ProgVars: \";\n if (auto mem = arg->get_memory_object()) {\n xocl::xocl(mem)->try_get_address_bank(physaddr, bank);\n }\n \/\/progvars are prefixed \"__xcl_gv_\", remove them before printing\n std::string argname = arg->get_name();\n std::string progvar_prefix = \"__xcl_gv_\";\n if (argname.find(progvar_prefix)!= std::string::npos) {\n argname = argname.substr(progvar_prefix.length());\n }\n sstr << argname << \" = 0x\" << std::hex << physaddr << \" \" << std::dec;\n ++eventargitint;\n }\n\n return sstr.str();\n}\n\napp_debug_view >*\nclGetKernelInfo()\n{\n std::vector *v = new std::vector ();\n auto delete_kdv_lamda = [v] {\n for (auto kdv : *v)\n delete kdv;\n delete v;\n };\n auto adv = new app_debug_view > (v, std::move(delete_kdv_lamda), false, \"\");\n\n std::vector selectedEventsVec;\n\n auto collect_kernel_events_lamda = [&selectedEventsVec] (cl_event aEvent) {\n xocl::event* e = xocl::xocl(aEvent);\n if (e->get_command_type() == CL_COMMAND_NDRANGE_KERNEL || e->get_command_type() == CL_COMMAND_TASK)\n selectedEventsVec.push_back(e);\n };\n\n auto add_edv_lambda = [v](xocl::event *event) {\n if (event!=nullptr) {\n try {\n cl_int evstatus = event->try_get_status();\n if (evstatus == CL_SUBMITTED || evstatus == CL_RUNNING) {\n auto exctx = event->get_execution_context();\n std::string kname = exctx->get_kernel()->get_name();\n\n bool is_scheduled = app_debug_track::getInstance()->try_get_data(event).m_start;\n uint32_t ncomplete = app_debug_track::getInstance()->try_get_data(event).m_ncomplete;\n std::string evstatusstr = is_scheduled ? \"Scheduled\" : \"Waiting\";\n v->push_back(new kernel_debug_view (kname, evstatusstr, exctx->get_num_work_groups(), ncomplete, getArgValueString(event)));\n }\n }\n catch (const xocl::error &ex) {\n v->push_back(new kernel_debug_view (\"None\", \"None\", 0, 0, ex.what()));\n }\n }\n };\n\n try {\n \/\/First collect the events of interest in a vector and then call debug actions on them\n \/\/for_each and debug action both need the lock on the tracker resulting in deadlock.\n app_debug_track::getInstance()->for_each(std::move(collect_kernel_events_lamda));\n std::for_each(selectedEventsVec.begin(), selectedEventsVec.end(), std::move(add_edv_lambda));\n }\n catch(const xocl::error& ex) {\n adv->setInvalidMsg(true, ex.what());\n }\n return adv;\n}\nbool\nisAppdebugEnabled()\n{\n return xrt::config::get_app_debug();\n}\n\nuint32_t getIPCountAddrNames(std::string& devUserName, int type, std::vector *baseAddress, std::vector * portNames) {\n debug_ip_layout *map;\n \/\/ Get the path to the device from the HAL\n \/\/ std::string path = \"\/sys\/bus\/pci\/devices\/\" + devUserName + \"\/debug_ip_layout\";\n std::string path = devUserName;\n std::ifstream ifs(path.c_str(), std::ifstream::binary);\n uint32_t count = 0;\n char buffer[debug_ip_layout_max_size];\n if( ifs.good() ) {\n \/\/sysfs max file size is debug_ip_layout_max_size\n ifs.read(buffer, debug_ip_layout_max_size);\n if (ifs.gcount() > 0) {\n map = (debug_ip_layout*)(buffer);\n for( unsigned int i = 0; i < map->m_count; i++ ) {\n if (map->m_debug_ip_data[i].m_type == type) {\n if(baseAddress)baseAddress->push_back(map->m_debug_ip_data[i].m_base_address);\n if(portNames) portNames->push_back((char*)map->m_debug_ip_data[i].m_name);\n ++count;\n }\n }\n }\n ifs.close();\n }\n return count;\n}\n\nstd::pair getCUNamePortName (std::vector& aSlotNames,\n std::vector< std::pair >& aCUNamePortNames) {\n \/\/Slotnames are of the format \"\/cuname\/portname\" or \"cuname\/portname\", split them and return in separate vector\n \/\/return max length of the cuname and port names\n size_t max1 = 0, max2 = 0;\n char sep = '\/';\n for (auto slotName: aSlotNames) {\n size_t found1;\n size_t start = 0;\n found1 = slotName.find(sep, 0);\n if (found1 == 0) {\n \/\/if the cuname starts with a '\/'\n start = 1;\n found1 = slotName.find(sep, 1);\n }\n if (found1 != std::string::npos) {\n aCUNamePortNames.emplace_back(slotName.substr(start, found1-start), slotName.substr(found1+1));\n }\n else {\n aCUNamePortNames.emplace_back(\"Unknown\", \"Unknown\");\n }\n \/\/Replace the name of the host-aim to something simple\n if (aCUNamePortNames.back().first.find(\"interconnect_host_aximm\") != std::string::npos) {\n aCUNamePortNames.pop_back();\n aCUNamePortNames.emplace_back(\"XDMA\", \"N\/A\");\n }\n\n \/\/ Use strlen() instead of length() because the strings taken from debug_ip_layout\n \/\/ are always 128 in length, where the end is full of null characters\n max1 = std::max(strlen(aCUNamePortNames.back().first.c_str()), max1);\n max2 = std::max(strlen(aCUNamePortNames.back().second.c_str()), max2);\n }\n return std::pair(max1, max2);\n}\n\nstruct aim_debug_view {\n unsigned long long int WriteBytes[XAIM_MAX_NUMBER_SLOTS];\n unsigned long long int WriteTranx[XAIM_MAX_NUMBER_SLOTS];\n unsigned long long int ReadBytes[XAIM_MAX_NUMBER_SLOTS];\n unsigned long long int ReadTranx[XAIM_MAX_NUMBER_SLOTS];\n\n unsigned long long int OutStandCnts[XAIM_MAX_NUMBER_SLOTS];\n unsigned long long int LastWriteAddr[XAIM_MAX_NUMBER_SLOTS];\n unsigned long long int LastWriteData[XAIM_MAX_NUMBER_SLOTS];\n unsigned long long int LastReadAddr[XAIM_MAX_NUMBER_SLOTS];\n unsigned long long int LastReadData[XAIM_MAX_NUMBER_SLOTS];\n unsigned int NumSlots;\n std::string DevUserName;\n std::string SysfsPath;\n aim_debug_view () {\n std::fill (WriteBytes, WriteBytes+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (WriteTranx, WriteTranx+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (ReadBytes, ReadBytes+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (ReadTranx, ReadTranx+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (OutStandCnts, OutStandCnts+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (LastWriteAddr, LastWriteAddr+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (LastWriteData, LastWriteData+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (LastReadAddr, LastReadAddr+XAIM_MAX_NUMBER_SLOTS, 0);\n std::fill (LastReadData, LastReadData+XAIM_MAX_NUMBER_SLOTS, 0);\n NumSlots = 0;\n DevUserName = \"\";\n }\n ~aim_debug_view() {}\n std::string getstring(int aVerbose = 0, int aJSONFormat = 0);\n};\n\nstd::string\naim_debug_view::getstring(int aVerbose, int aJSONFormat) {\n std::stringstream sstr;\n std::vector slotNames;\n std::vector< std::pair > cuNameportNames;\n\n std::string quotes;\n if (aJSONFormat) quotes = \"\\\"\";\n else quotes = \"\";\n if (NumSlots == 0) {\n if (aJSONFormat) {\n return \"[]\";\n }\n else {\n sstr << \"No AIM found on the platform \\n\";\n return sstr.str();\n }\n }\n\n \/\/ unsigned int numSlots = \n getIPCountAddrNames(SysfsPath, AXI_MM_MONITOR, nullptr, &slotNames);\n std::pair widths = getCUNamePortName(slotNames, cuNameportNames);\n\n if (aJSONFormat) {\n sstr << \"[\"; \/\/spm list\n for (unsigned int i = 0; i 0 ? \",\" : \"\") << \"{\";\n sstr << quotes << \"RegionCU\" << quotes << \" : \" << quotes << cuNameportNames[i].first << quotes << \",\";\n sstr << quotes << \"TypePort\" << quotes << \" : \" << quotes << cuNameportNames[i].second.c_str() << quotes << \",\";\n sstr << quotes << \"WriteBytes\" << quotes << \" : \" << quotes << WriteBytes[i] << quotes << \",\";\n sstr << quotes << \"WriteTranx\" << quotes << \" : \" << quotes << WriteTranx[i] << quotes << \",\";\n sstr << quotes << \"ReadBytes\" << quotes << \" : \" << quotes << ReadBytes[i] << quotes << \",\";\n sstr << quotes << \"ReadTranx\" << quotes << \" : \" << quotes << ReadTranx[i] << quotes << \",\";\n sstr << quotes << \"OutstandingCnt\" << quotes << \" : \" << quotes << OutStandCnts[i] << quotes << \",\";\n sstr << quotes << \"LastWrAddr\" << quotes << \" : \" << quotes << \"0x\" << std::hex << LastWriteAddr[i] << quotes << \",\";\n sstr << quotes << \"LastWrData\" << quotes << \" : \" << quotes << \"0x\" << LastWriteData[i] << quotes << \",\";\n sstr << quotes << \"LastRdAddr\" << quotes << \" : \" << quotes << \"0x\" << LastReadAddr[i] << quotes << \",\";\n sstr << quotes << \"LastRdData\" << quotes << \" : \" << quotes << \"0x\" << LastReadData[i] << quotes << std::dec ;\n sstr << \"}\";\n }\n sstr << \"]\";\n }\n else {\n sstr<< \"Performance Monitor Counters\\n\";\n int col1 = std::max(widths.first, strlen(\"Region or CU\")) + 4;\n int col2 = std::max(widths.second, strlen(\"Type or Port\"));\n\n sstr << std::left\n << std::setw(col1) << \"Region or CU\"\n << \" \" << std::setw(col2) << \"Type or Port\"\n << \" \" << std::setw(16) << \"Write Bytes\"\n << \" \" << std::setw(16) << \"Write Tranx.\"\n << \" \" << std::setw(16) << \"Read Bytes\"\n << \" \" << std::setw(16) << \"Read Tranx.\"\n << \" \" << std::setw(16) << \"Outstanding Cnt\"\n << \" \" << std::setw(16) << \"Last Wr Addr\"\n << \" \" << std::setw(16) << \"Last Wr Data\"\n << \" \" << std::setw(16) << \"Last Rd Addr\"\n << \" \" << std::setw(16) << \"Last Rd Data\"\n << std::endl;\n for (unsigned int i = 0; i*\nclGetDebugCounters() {\n xclDebugCountersResults debugResults = {0};\n\n if (isEmulationMode()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"xstatus is not supported in emulation flow\");\n return adv;\n }\n\n if (!xdp::active()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Runtime instance not yet created\");\n return adv;\n }\n auto rts = xdp::RTSingleton::Instance();\n if (!rts) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Error: Runtime instance not available\");\n return adv;\n }\n\n auto platform = rts->getcl_platform_id();\n \/\/ Iterates over all devices, but assumes only one device\n memset(&debugResults,0, sizeof(xclDebugCountersResults));\n std::string subdev = \"icap\";\n std::string entry = \"debug_ip_layout\";\n std::string sysfs_open_path;\n for (auto device : platform->get_device_range()) {\n if (device->is_active()) {\n \/\/memset(&debugResults,0, sizeof(xclDebugCountersResults));\n \/\/At this point we deal with only one deviceyy\n device->get_xrt_device()->debugReadIPStatus(XCL_DEBUG_READ_TYPE_AIM, &debugResults);\n sysfs_open_path = device->get_xrt_device()->getSysfsPath(subdev, entry).get();\n \/\/ret |= xdp::profile::device::debugReadIPStatus(device, XCL_DEBUG_READ_TYPE_AIM, &debugResults);\n }\n }\n\n auto aim_view = new aim_debug_view ();\n std::copy(debugResults.WriteBytes, debugResults.WriteBytes+XAIM_MAX_NUMBER_SLOTS, aim_view->WriteBytes);\n std::copy(debugResults.WriteTranx, debugResults.WriteTranx+XAIM_MAX_NUMBER_SLOTS, aim_view->WriteTranx);\n std::copy(debugResults.ReadBytes, debugResults.ReadBytes+XAIM_MAX_NUMBER_SLOTS, aim_view->ReadBytes);\n std::copy(debugResults.ReadTranx, debugResults.ReadTranx+XAIM_MAX_NUMBER_SLOTS, aim_view->ReadTranx);\n std::copy(debugResults.OutStandCnts, debugResults.OutStandCnts+XAIM_MAX_NUMBER_SLOTS, aim_view->OutStandCnts);\n std::copy(debugResults.LastWriteAddr, debugResults.LastWriteAddr+XAIM_MAX_NUMBER_SLOTS, aim_view->LastWriteAddr);\n std::copy(debugResults.LastWriteData, debugResults.LastWriteData+XAIM_MAX_NUMBER_SLOTS, aim_view->LastWriteData);\n std::copy(debugResults.LastReadAddr, debugResults.LastReadAddr+XAIM_MAX_NUMBER_SLOTS, aim_view->LastReadAddr);\n std::copy(debugResults.LastReadData, debugResults.LastReadData+XAIM_MAX_NUMBER_SLOTS, aim_view->LastReadData);\n aim_view->NumSlots = debugResults.NumSlots;\n aim_view->DevUserName = debugResults.DevUserName;\n aim_view->SysfsPath = sysfs_open_path;\n\n auto adv = new app_debug_view (aim_view, [aim_view](){delete aim_view;}, false, \"\");\n\n return adv;\n}\n\n\/\/ Streaming counter view\n\nstruct asm_debug_view {\n unsigned long long int StrNumTranx [XASM_MAX_NUMBER_SLOTS];\n unsigned long long int StrDataBytes [XASM_MAX_NUMBER_SLOTS];\n unsigned long long int StrBusyCycles [XASM_MAX_NUMBER_SLOTS];\n unsigned long long int StrStallCycles [XASM_MAX_NUMBER_SLOTS];\n unsigned long long int StrStarveCycles[XASM_MAX_NUMBER_SLOTS];\n\n unsigned int NumSlots ;\n std::vector > ConnectionNames;\n std::string DevUserName ;\n std::string SysfsPath;\n\n asm_debug_view() \n {\n std::fill(StrNumTranx, StrNumTranx + XASM_MAX_NUMBER_SLOTS, 0);\n std::fill(StrDataBytes, StrDataBytes + XASM_MAX_NUMBER_SLOTS, 0);\n std::fill(StrBusyCycles, StrBusyCycles + XASM_MAX_NUMBER_SLOTS, 0);\n std::fill(StrStallCycles, StrStallCycles + XASM_MAX_NUMBER_SLOTS, 0);\n std::fill(StrStarveCycles, StrStarveCycles + XASM_MAX_NUMBER_SLOTS, 0);\n\n NumSlots = 0;\n }\n ~asm_debug_view() { }\n std::string getstring(int aVerbose = 0, int aJSONFormat = 0);\n \n std::string getJSONString(bool aVerbose) ;\n std::string getXGDBString(bool aVerbose) ;\n} ;\n\nstd::string\nasm_debug_view::getstring(int aVerbose, int aJSONFormat) {\n if (aJSONFormat) return getJSONString(aVerbose != 0 ? true : false) ; \n else return getXGDBString(aVerbose != 0 ? true : false) ;\n}\n\nstd::string\nasm_debug_view::getJSONString(bool aVerbose) {\n std::stringstream sstr ;\n\n sstr << \"[\" ;\n for (unsigned int i = 0 ; i < NumSlots ; ++i)\n {\n if (i > 0) sstr << \",\" ;\n sstr << \"{\" ;\n sstr << \"\\\"\" << \"StrNumTransactions\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << StrNumTranx[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"StrDataBytes\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << StrDataBytes[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"StrBusyCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << StrBusyCycles[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"StrStallCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << StrStallCycles[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"StrStarveCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << StrStarveCycles[i] << \"\\\"\" ;\n sstr << \"}\" ;\n }\n sstr << \"]\" ;\n\n return sstr.str();\n}\n\nstd::string\nasm_debug_view::getXGDBString(bool aVerbose) {\n std::stringstream sstr;\n\n \/\/ Calculate the width for formatting the columns\n size_t maxMasterWidth = 0 ;\n size_t maxSlaveWidth = 0 ;\n for (unsigned int i = 0 ; i < NumSlots ; ++i)\n {\n maxMasterWidth = std::max(ConnectionNames[i].first.length(), maxMasterWidth);\n maxSlaveWidth = std::max(ConnectionNames[i].second.length(), maxSlaveWidth);\n }\n\n size_t col1 = std::max(strlen(\"Stream Master\"), maxMasterWidth) + 4 ;\n size_t col2 = std::max(strlen(\"Stream Slave\"), maxSlaveWidth) ;\n\n sstr << \"Streaming Performance Monitor Counters\\n\" ;\n sstr << std::left\n << std::setw(col1) << \"Stream Master\"\n << \" \" << std::setw(col2) << \"Stream Slave\"\n << \" \" << std::setw(32) << \"Number of Transactions\"\n << \" \" << std::setw(16) << \"Data Bytes\"\n << \" \" << std::setw(16) << \"Busy Cycles\"\n << \" \" << std::setw(16) << \"Stall Cycles\"\n << \" \" << std::setw(16) << \"Starve Cycles\"\n << std::endl ;\n for (unsigned int i = 0 ; i < NumSlots ; ++i)\n {\n sstr << std::left\n\t << std::setw(col1) << ConnectionNames[i].first\n\t << \" \" << std::setw(col2) << ConnectionNames[i].second\n\t << \" \" << std::setw(32) << StrNumTranx[i]\n\t << \" \" << std::setw(16) << StrDataBytes[i]\n\t << \" \" << std::setw(16) << StrBusyCycles[i]\n\t << \" \" << std::setw(16) << StrStallCycles[i]\n\t << \" \" << std::setw(16) << StrStarveCycles[i]\n\t << std::endl ;\n }\n\n return sstr.str() ;\n}\n\napp_debug_view*\nclGetDebugStreamCounters()\n{\n \/\/ Check for error conditions where we cannot read the streaming counters\n if (isEmulationMode()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"xstatus is not supported in emulation flow\");\n return adv;\n }\n if (!xdp::active()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Runtime instance not yet created\");\n return adv;\n }\n auto rts = xdp::RTSingleton::Instance();\n if (!rts) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Error: Runtime instance not available\");\n return adv;\n }\n\n xclStreamingDebugCountersResults streamingDebugCounters; \n memset(&streamingDebugCounters, 0, sizeof(xclStreamingDebugCountersResults));\n std::string subdev = \"icap\";\n std::string entry = \"debug_ip_layout\";\n std::string sysfs_open_path;\n auto platform = rts->getcl_platform_id();\n for (auto device : platform->get_device_range())\n {\n if (device->is_active())\n {\n \/\/ At this point, we are dealing with only one device\n device->get_xrt_device()->debugReadIPStatus(XCL_DEBUG_READ_TYPE_ASM, &streamingDebugCounters);\n sysfs_open_path = device->get_xrt_device()->getSysfsPath(subdev, entry).get();\n \/\/ret |= xdp::profile::device::debugReadIPStatus(device, XCL_DEBUG_READ_TYPE_ASM, &streamingDebugCounters);\n }\n }\n\n auto asm_view = new asm_debug_view () ;\n \n std::copy(streamingDebugCounters.StrNumTranx,\n\t streamingDebugCounters.StrNumTranx+XASM_MAX_NUMBER_SLOTS,\n\t asm_view->StrNumTranx);\n std::copy(streamingDebugCounters.StrDataBytes,\n\t streamingDebugCounters.StrDataBytes+XASM_MAX_NUMBER_SLOTS,\n\t asm_view->StrDataBytes);\n std::copy(streamingDebugCounters.StrBusyCycles,\n\t streamingDebugCounters.StrBusyCycles+XASM_MAX_NUMBER_SLOTS,\n\t asm_view->StrBusyCycles);\n std::copy(streamingDebugCounters.StrStallCycles,\n\t streamingDebugCounters.StrStallCycles+XASM_MAX_NUMBER_SLOTS,\n\t asm_view->StrStallCycles);\n std::copy(streamingDebugCounters.StrStarveCycles,\n\t streamingDebugCounters.StrStarveCycles+XASM_MAX_NUMBER_SLOTS,\n\t asm_view->StrStarveCycles);\n \n asm_view->NumSlots = streamingDebugCounters.NumSlots ;\n asm_view->DevUserName = streamingDebugCounters.DevUserName ;\n asm_view->SysfsPath = sysfs_open_path;\n\n std::vector slotNames;\n getIPCountAddrNames(sysfs_open_path, AXI_STREAM_MONITOR, nullptr, &slotNames);\n\n for (auto& s : slotNames)\n {\n size_t found ;\n found = s.find(IP_LAYOUT_SEP, 0) ;\n if (found != std::string::npos)\n asm_view->ConnectionNames.push_back(std::make_pair(s.substr(0, found), s.substr(found+1)));\n else\n asm_view->ConnectionNames.push_back(std::make_pair(\"Unknown\", \"Unknown\"));\n }\n\n auto adv = new app_debug_view(asm_view, [asm_view]() { delete asm_view;}, false, \"\") ;\n return adv ;\n}\n\n\/\/ Accel monitor\nstruct am_debug_view {\n unsigned long long CuExecCount [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuExecCycles [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuBusyCycles [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuMaxParallelIter [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuStallExtCycles [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuStallIntCycles [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuStallStrCycles [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuMinExecCycles [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuMaxExecCycles [XAM_MAX_NUMBER_SLOTS];\n unsigned long long CuStartCount [XAM_MAX_NUMBER_SLOTS];\n\n unsigned int NumSlots ;\n std::string DevUserName ;\n std::string SysfsPath;\n\n am_debug_view() \n {\n std::fill(CuExecCount, CuExecCount + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuExecCycles, CuExecCycles + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuBusyCycles, CuBusyCycles + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuMaxParallelIter, CuMaxParallelIter + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuStallExtCycles, CuStallExtCycles + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuStallIntCycles, CuStallIntCycles + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuStallStrCycles, CuStallStrCycles + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuMinExecCycles, CuMinExecCycles + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuMaxExecCycles, CuMaxExecCycles + XAM_MAX_NUMBER_SLOTS, 0);\n std::fill(CuStartCount, CuStartCount + XAM_MAX_NUMBER_SLOTS, 0);\n\n NumSlots = 0;\n }\n ~am_debug_view() { }\n std::string getstring(int aVerbose = 0, int aJSONFormat = 0);\n \n std::string getJSONString(bool aVerbose) ;\n std::string getXGDBString(bool aVerbose) ;\n} ;\n\nstd::string\nam_debug_view::getstring(int aVerbose, int aJSONFormat) {\n if (aJSONFormat) return getJSONString(aVerbose != 0 ? true : false) ; \n else return getXGDBString(aVerbose != 0 ? true : false) ;\n}\n\nstd::string\nam_debug_view::getJSONString(bool aVerbose) {\n std::stringstream sstr ;\n std::vector slotNames;\n getIPCountAddrNames(SysfsPath, ACCEL_MONITOR, nullptr, &slotNames);\n\n sstr << \"[\" ;\n for (unsigned int i = 0 ; i < NumSlots ; ++i)\n {\n if (i > 0) sstr << \",\" ;\n sstr << \"{\" ;\n sstr << \"\\\"\" << \"CuName\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << slotNames[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"CuExecCount\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuExecCount[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"CuExecCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuExecCycles[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"CuBusyCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuBusyCycles[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"CuMaxParallelIter\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuMaxParallelIter[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"CuStallExtCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuStallExtCycles[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"CuStallIntCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuStallIntCycles[i] << \"\\\"\" << \",\" ;\n sstr << \"\\\"\" << \"CuStallStrCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuStallStrCycles[i] << \"\\\"\" ;\n sstr << \"\\\"\" << \"CuMinExecCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuMinExecCycles[i] << \"\\\"\" ;\n sstr << \"\\\"\" << \"CuMaxExecCycles\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuMaxExecCycles[i] << \"\\\"\" ;\n sstr << \"\\\"\" << \"CuStartCount\" << \"\\\"\" << \":\" \n\t << \"\\\"\" << CuStartCount[i] << \"\\\"\" ;\n sstr << \"}\" ;\n }\n sstr << \"]\" ;\n\n return sstr.str();\n}\n\nstd::string\nam_debug_view::getXGDBString(bool aVerbose) {\n std::stringstream sstr;\n std::vector slotNames;\n getIPCountAddrNames(SysfsPath, ACCEL_MONITOR, nullptr, &slotNames);\n int col = 11;\n std::for_each(slotNames.begin(), slotNames.end(), [&](std::string& slotName){\n col = std::max(col, (int)slotName.length() + 4);\n });\n \n\n sstr << \"Kernel Activities\\n\" ;\n sstr << std::left\n << std::setw(col) << \"CU Name\"\n << \" \" << std::setw(16) << \"Exec Count\" \n << \" \" << std::setw(16) << \"Exec Cycles\" \n << \" \" << std::setw(16) << \"Busy Cycles\" \n << \" \" << std::setw(16) << \"Max Parallels\" \n << \" \" << std::setw(16) << \"Ext Stall Cycles\"\n << \" \" << std::setw(16) << \"Int Stall Cycles\"\n << \" \" << std::setw(16) << \"Str Stall Cycles\"\n << \" \" << std::setw(16) << \"Min Exec Cycles\"\n << \" \" << std::setw(16) << \"Max Exec Cycles\"\n << \" \" << std::setw(16) << \"Start Count\"\n << std::endl ;\n for (unsigned int i = 0 ; i < NumSlots ; ++i)\n {\n unsigned long long minCycle = (CuMinExecCycles[i] == 0xFFFFFFFFFFFFFFFF) ? 0 : CuMinExecCycles[i];\n sstr << std::left\n\t << std::setw(col) << slotNames[i]\n\t << \" \" << std::setw(16) << CuExecCount[i]\n << \" \" << std::setw(16) << CuExecCycles[i]\n << \" \" << std::setw(16) << CuBusyCycles[i]\n << \" \" << std::setw(16) << CuMaxParallelIter[i]\n\t << \" \" << std::setw(16) << CuStallExtCycles[i]\n\t << \" \" << std::setw(16) << CuStallIntCycles[i]\n << \" \" << std::setw(16) << CuStallStrCycles[i]\n << \" \" << std::setw(16) << minCycle\n << \" \" << std::setw(16) << CuMaxExecCycles[i]\n << \" \" << std::setw(16) << CuStartCount[i]\n\t << std::endl ;\n }\n\n return sstr.str() ;\n}\n\napp_debug_view*\nclGetDebugAccelMonitorCounters()\n{\n \/\/ Check for error conditions where we cannot read the streaming counters\n if (isEmulationMode()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"xstatus is not supported in emulation flow\");\n return adv;\n }\n if (!xdp::active()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Runtime instance not yet created\");\n return adv;\n }\n auto rts = xdp::RTSingleton::Instance();\n if (!rts) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Error: Runtime instance not available\");\n return adv;\n }\n\n xclAccelMonitorCounterResults amCounters; \n memset(&amCounters, 0, sizeof(xclAccelMonitorCounterResults));\n\n std::string subdev = \"icap\";\n std::string entry = \"debug_ip_layout\";\n std::string sysfs_open_path;\n auto platform = rts->getcl_platform_id();\n for (auto device : platform->get_device_range())\n {\n if (device->is_active())\n {\n \/\/ At this point, we are dealing with only one device\n device->get_xrt_device()->debugReadIPStatus(XCL_DEBUG_READ_TYPE_AM, &amCounters);\n sysfs_open_path = device->get_xrt_device()->getSysfsPath(subdev, entry).get();\n \/\/ ret |= xdp::profile::device::debugReadIPStatus(device, XCL_DEBUG_READ_TYPE_AM, &amCounters);\n }\n }\n\n auto am_view = new am_debug_view() ;\n am_view->SysfsPath = sysfs_open_path;\n \n std::copy(amCounters.CuExecCount,\n\t amCounters.CuExecCount+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuExecCount);\n std::copy(amCounters.CuExecCycles,\n\t amCounters.CuExecCycles+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuExecCycles);\n std::copy(amCounters.CuBusyCycles,\n\t amCounters.CuBusyCycles+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuBusyCycles);\n std::copy(amCounters.CuMaxParallelIter,\n\t amCounters.CuMaxParallelIter+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuMaxParallelIter);\n std::copy(amCounters.CuStallExtCycles,\n\t amCounters.CuStallExtCycles+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuStallExtCycles);\n std::copy(amCounters.CuStallIntCycles,\n\t amCounters.CuStallIntCycles+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuStallIntCycles);\n std::copy(amCounters.CuStallStrCycles,\n\t amCounters.CuStallStrCycles+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuStallStrCycles);\n std::copy(amCounters.CuMinExecCycles,\n\t amCounters.CuMinExecCycles+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuMinExecCycles);\n std::copy(amCounters.CuMaxExecCycles,\n\t amCounters.CuMaxExecCycles+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuMaxExecCycles);\n std::copy(amCounters.CuStartCount,\n\t amCounters.CuStartCount+XAM_MAX_NUMBER_SLOTS,\n\t am_view->CuStartCount);\n \n am_view->NumSlots = amCounters.NumSlots ;\n am_view->DevUserName = amCounters.DevUserName ;\n\n auto adv = new app_debug_view(am_view, [am_view]() { delete am_view;}, false, \"\") ;\n\n return adv ;\n}\n\/\/ End of Accel monitor\n\n\nstruct lapc_debug_view {\n unsigned int OverallStatus[XLAPC_MAX_NUMBER_SLOTS];\n unsigned int CumulativeStatus[XLAPC_MAX_NUMBER_SLOTS][4];\n unsigned int SnapshotStatus[XLAPC_MAX_NUMBER_SLOTS][4];\n unsigned int NumSlots;\n std::string DevUserName;\n std::string SysfsPath;\n lapc_debug_view () {\n std::fill (OverallStatus, OverallStatus+XLAPC_MAX_NUMBER_SLOTS, 0);\n for (auto i = 0; i lapcSlotNames;\n std::vector< std::pair > cuNameportNames;\n\n std::string quotes;\n if (aJSONFormat) quotes = \"\\\"\";\n else quotes = \"\";\n\n if (NumSlots == 0) {\n if (aJSONFormat) {\n return \"[]\";\n }\n else {\n sstr << \"No LAPC found on the platform \\n\";\n return sstr.str();\n }\n }\n\n \/\/ unsigned int numSlots = \n getIPCountAddrNames(SysfsPath, LAPC, nullptr, &lapcSlotNames);\n std::pair widths = getCUNamePortName(lapcSlotNames, cuNameportNames);\n\n bool violations_found = false;\n bool invalid_codes = false;\n\n if (aJSONFormat) {\n sstr << \"[\"; \/\/spm list\n for (unsigned int i = 0; i 0 ? \",\" : \"\") << \"{\";\n sstr << quotes << \"CUName\" << quotes << \" : \" << quotes << cuNameportNames[i].first << quotes << \",\";\n sstr << quotes << \"AXIPortname\" << quotes << \" : \" << quotes << cuNameportNames[i].second << quotes << \",\";\n if (!xclAXICheckerCodes::isValidAXICheckerCodes(OverallStatus[i],\n SnapshotStatus[i], CumulativeStatus[i])) {\n sstr << quotes << \"FirstViolation\" << quotes << \" : \" << quotes << \"Invalid Codes\" << quotes << \",\";\n sstr << quotes << \"OtherViolations\" << quotes << \" : \" << quotes << \"Invalid Codes\" << quotes ;\n }\n else {\n if (OverallStatus[i]) {\n std::string tstr;\n unsigned int tCummStatus[4] = {0};\n \/\/snapshot reflects first violation, cumulative has all violations\n tstr = xclAXICheckerCodes::decodeAXICheckerCodes(SnapshotStatus[i]);\n tstr = (tstr == \"\") ? \"None\" : tstr;\n sstr << quotes << \"FirstViolation\" << quotes << \" : \" << quotes << tstr << quotes << \",\";\n\n std::transform(CumulativeStatus[i], CumulativeStatus[i]+4, SnapshotStatus[i], tCummStatus, std::bit_xor());\n tstr = xclAXICheckerCodes::decodeAXICheckerCodes(tCummStatus);\n tstr = (tstr == \"\") ? \"None\" : tstr;\n sstr << quotes << \"OtherViolations\" << quotes << \" : \" << quotes << tstr << quotes ;\n }\n else {\n sstr << quotes << \"FirstViolation\" << quotes << \" : \" << quotes << \"None\" << quotes << \",\";\n sstr << quotes << \"OtherViolations\" << quotes << \" : \" << quotes << \"None\" << quotes ;\n }\n }\n sstr << \"}\";\n }\/\/for\n sstr << \"]\";\n }\n else {\n int col1 = std::max(widths.first, strlen(\"CU Name\")) + 4;\n int col2 = std::max(widths.second, strlen(\"AXI Portname\"));\n\n sstr << \"Light-weight AXI protocol checker status\\n\";\n for (unsigned int i = 0; i());\n sstr << \" Other violations: \\n\";\n std::string tstr = xclAXICheckerCodes::decodeAXICheckerCodes(tCummStatus);\n if (tstr == \"\") {\n sstr << \" \" << \"None\";\n }\n else {\n sstr << \" \" << tstr;\n }\n violations_found = true;\n }\n }\n if (!violations_found && !invalid_codes) {\n sstr << \"No AXI violations found \\n\";\n }\n if (violations_found && aVerbose && !invalid_codes) {\n sstr << \"\\n\";\n sstr << std::left\n << std::setw(col1) << \"CU Name\"\n << \" \" << std::setw(col2) << \"AXI Portname\"\n << \" \" << std::setw(16) << \"Overall Status\"\n << \" \" << std::setw(16) << \"Snapshot[0]\"\n << \" \" << std::setw(16) << \"Snapshot[1]\"\n << \" \" << std::setw(16) << \"Snapshot[2]\"\n << \" \" << std::setw(16) << \"Snapshot[3]\"\n << \" \" << std::setw(16) << \"Cumulative[0]\"\n << \" \" << std::setw(16) << \"Cumulative[1]\"\n << \" \" << std::setw(16) << \"Cumulative[2]\"\n << \" \" << std::setw(16) << \"Cumulative[3]\"\n << std::endl;\n for (unsigned int i = 0; i*\nclGetDebugCheckers() {\n xclDebugCheckersResults debugCheckers;\n\n if (isEmulationMode()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"xstatus is not supported in emulation flow\");\n return adv;\n }\n if (!xdp::active()) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Runtime instance not yet created\");\n return adv;\n }\n auto rts = xdp::RTSingleton::Instance();\n if (!rts) {\n auto adv = new app_debug_view(nullptr, nullptr, true, \"Error: Runtime instance not available\");\n return adv;\n }\n std::string subdev = \"icap\";\n std::string entry = \"debug_ip_layout\";\n std::string sysfs_open_path;\n auto platform = rts->getcl_platform_id();\n \/\/ Iterates over all devices, but assumes only one device\n memset(&debugCheckers,0, sizeof(xclDebugCheckersResults));\n for (auto device : platform->get_device_range()) {\n if (device->is_active()) {\n \/\/memset(&debugCheckers,0, sizeof(xclDebugCheckersResults));\n \/\/At this point we deal with only one deviceyy\n device->get_xrt_device()->debugReadIPStatus(XCL_DEBUG_READ_TYPE_LAPC, &debugCheckers);\n sysfs_open_path = device->get_xrt_device()->getSysfsPath(subdev, entry).get();\n \/\/ret |= xdp::profile::device::debugReadIPStatus(device, XCL_DEBUG_READ_TYPE_LAPC, &debugCheckers);\n }\n }\n\n auto lapc_view = new lapc_debug_view ();\n std::copy(debugCheckers.OverallStatus, debugCheckers.OverallStatus+XLAPC_MAX_NUMBER_SLOTS, lapc_view->OverallStatus);\n for (auto i = 0; iCumulativeStatus[i]);\n for (auto i = 0; iSnapshotStatus[i]);\n lapc_view->NumSlots = debugCheckers.NumSlots;\n lapc_view->DevUserName = debugCheckers.DevUserName;\n lapc_view->SysfsPath = sysfs_open_path;\n auto adv = new app_debug_view (lapc_view, [lapc_view](){delete lapc_view;}, false, \"\");\n return adv;\n}\n}\/\/appdebug\n\/\/Debug functions\n\n\n","avg_line_length":38.1564699513,"max_line_length":190,"alphanum_fraction":0.6428378858} {"size":8999,"ext":"cpp","lang":"C++","max_stars_count":1963.0,"content":"\/*\n Stream.cpp - adds parsing methods to Stream class\n Copyright (c) 2008 David A. Mellis. All right reserved.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n Created July 2011\n parsing functions based on TextFinder library by Michael Margolis\n\n findMulti\/findUntil routines written by Jim Leonard\/Xuth\n *\/\n\n#include \"Arduino.h\"\n#include \"Stream.h\"\n\n#define PARSE_TIMEOUT 1000 \/\/ default number of milli-seconds to wait\n\n\/\/ private method to read stream with timeout\nint Stream::timedRead()\n{\n int c;\n _startMillis = millis();\n do {\n c = read();\n if (c >= 0) {\n return c;\n }\n } while (millis() - _startMillis < _timeout);\n return -1; \/\/ -1 indicates timeout\n}\n\n\/\/ private method to peek stream with timeout\nint Stream::timedPeek()\n{\n int c;\n _startMillis = millis();\n do {\n c = peek();\n if (c >= 0) {\n return c;\n }\n } while (millis() - _startMillis < _timeout);\n return -1; \/\/ -1 indicates timeout\n}\n\n\/\/ returns peek of the next digit in the stream or -1 if timeout\n\/\/ discards non-numeric characters\nint Stream::peekNextDigit(LookaheadMode lookahead, bool detectDecimal)\n{\n int c;\n while (1) {\n c = timedPeek();\n\n if (c < 0 ||\n c == '-' ||\n (c >= '0' && c <= '9') ||\n (detectDecimal && c == '.')) {\n return c;\n }\n\n switch (lookahead) {\n case SKIP_NONE: return -1; \/\/ Fail code.\n case SKIP_WHITESPACE:\n switch (c) {\n case ' ':\n case '\\t':\n case '\\r':\n case '\\n': break;\n default: return -1; \/\/ Fail code.\n }\n case SKIP_ALL:\n break;\n }\n read(); \/\/ discard non-numeric\n }\n}\n\n\/\/ Public Methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Stream::setTimeout(unsigned long timeout) \/\/ sets the maximum number of milliseconds to wait\n{\n _timeout = timeout;\n}\n\n\/\/ find returns true if the target string is found\nbool Stream::find(const char *target)\n{\n return findUntil(target, strlen(target), NULL, 0);\n}\n\n\/\/ reads data from the stream until the target string of given length is found\n\/\/ returns true if target string is found, false if timed out\nbool Stream::find(const char *target, size_t length)\n{\n return findUntil(target, length, NULL, 0);\n}\n\n\/\/ as find but search ends if the terminator string is found\nbool Stream::findUntil(const char *target, const char *terminator)\n{\n return findUntil(target, strlen(target), terminator, strlen(terminator));\n}\n\n\/\/ reads data from the stream until the target string of the given length is found\n\/\/ search terminated if the terminator string is found\n\/\/ returns true if target string is found, false if terminated or timed out\nbool Stream::findUntil(const char *target, size_t targetLen, const char *terminator, size_t termLen)\n{\n if (terminator == NULL) {\n MultiTarget t[1] = {{target, targetLen, 0}};\n return findMulti(t, 1) == 0 ? true : false;\n } else {\n MultiTarget t[2] = {{target, targetLen, 0}, {terminator, termLen, 0}};\n return findMulti(t, 2) == 0 ? true : false;\n }\n}\n\n\/\/ returns the first valid (long) integer value from the current position.\n\/\/ lookahead determines how parseInt looks ahead in the stream.\n\/\/ See LookaheadMode enumeration at the top of the file.\n\/\/ Lookahead is terminated by the first character that is not a valid part of an integer.\n\/\/ Once parsing commences, 'ignore' will be skipped in the stream.\nlong Stream::parseInt(LookaheadMode lookahead, char ignore)\n{\n bool isNegative = false;\n long value = 0;\n int c;\n\n c = peekNextDigit(lookahead, false);\n \/\/ ignore non numeric leading characters\n if (c < 0) {\n return 0; \/\/ zero returned if timeout\n }\n\n do {\n if (c == ignore)\n ; \/\/ ignore this character\n else if (c == '-') {\n isNegative = true;\n } else if (c >= '0' && c <= '9') { \/\/ is c a digit?\n value = value * 10 + c - '0';\n }\n read(); \/\/ consume the character we got with peek\n c = timedPeek();\n } while ((c >= '0' && c <= '9') || c == ignore);\n\n if (isNegative) {\n value = -value;\n }\n return value;\n}\n\n\/\/ as parseInt but returns a floating point value\nfloat Stream::parseFloat(LookaheadMode lookahead, char ignore)\n{\n bool isNegative = false;\n bool isFraction = false;\n long value = 0;\n int c;\n float fraction = 1.0;\n\n c = peekNextDigit(lookahead, true);\n \/\/ ignore non numeric leading characters\n if (c < 0) {\n return 0; \/\/ zero returned if timeout\n }\n\n do {\n if (c == ignore)\n ; \/\/ ignore\n else if (c == '-') {\n isNegative = true;\n } else if (c == '.') {\n isFraction = true;\n } else if (c >= '0' && c <= '9') { \/\/ is c a digit?\n value = value * 10 + c - '0';\n if (isFraction) {\n fraction *= 0.1;\n }\n }\n read(); \/\/ consume the character we got with peek\n c = timedPeek();\n } while ((c >= '0' && c <= '9') || (c == '.' && !isFraction) || c == ignore);\n\n if (isNegative) {\n value = -value;\n }\n if (isFraction) {\n return value * fraction;\n } else {\n return value;\n }\n}\n\n\/\/ read characters from stream into buffer\n\/\/ terminates if length characters have been read, or timeout (see setTimeout)\n\/\/ returns the number of characters placed in the buffer\n\/\/ the buffer is NOT null terminated.\n\/\/\nsize_t Stream::readBytes(char *buffer, size_t length)\n{\n size_t count = 0;\n while (count < length) {\n int c = timedRead();\n if (c < 0) {\n break;\n }\n *buffer++ = (char)c;\n count++;\n }\n return count;\n}\n\n\n\/\/ as readBytes with terminator character\n\/\/ terminates if length characters have been read, timeout, or if the terminator character detected\n\/\/ returns the number of characters placed in the buffer (0 means no valid data found)\n\nsize_t Stream::readBytesUntil(char terminator, char *buffer, size_t length)\n{\n if (length < 1) {\n return 0;\n }\n size_t index = 0;\n while (index < length) {\n int c = timedRead();\n if (c < 0 || c == terminator) {\n break;\n }\n *buffer++ = (char)c;\n index++;\n }\n return index; \/\/ return number of characters, not including null terminator\n}\n\nString Stream::readString()\n{\n String ret;\n int c = timedRead();\n while (c >= 0) {\n ret += (char)c;\n c = timedRead();\n }\n return ret;\n}\n\nString Stream::readStringUntil(char terminator)\n{\n String ret;\n int c = timedRead();\n while (c >= 0 && c != terminator) {\n ret += (char)c;\n c = timedRead();\n }\n return ret;\n}\n\nint Stream::findMulti(struct Stream::MultiTarget *targets, int tCount)\n{\n \/\/ any zero length target string automatically matches and would make\n \/\/ a mess of the rest of the algorithm.\n for (struct MultiTarget *t = targets; t < targets + tCount; ++t) {\n if (t->len <= 0) {\n return t - targets;\n }\n }\n\n while (1) {\n int c = timedRead();\n if (c < 0) {\n return -1;\n }\n\n for (struct MultiTarget *t = targets; t < targets + tCount; ++t) {\n \/\/ the simple case is if we match, deal with that first.\n if (c == t->str[t->index]) {\n if (++t->index == t->len) {\n return t - targets;\n } else {\n continue;\n }\n }\n\n \/\/ if not we need to walk back and see if we could have matched further\n \/\/ down the stream (ie '1112' doesn't match the first position in '11112'\n \/\/ but it will match the second position so we can't just reset the current\n \/\/ index to 0 when we find a mismatch.\n if (t->index == 0) {\n continue;\n }\n\n int origIndex = t->index;\n do {\n --t->index;\n \/\/ first check if current char works against the new current index\n if (c != t->str[t->index]) {\n continue;\n }\n\n \/\/ if it's the only char then we're good, nothing more to check\n if (t->index == 0) {\n t->index++;\n break;\n }\n\n \/\/ otherwise we need to check the rest of the found string\n int diff = origIndex - t->index;\n size_t i;\n for (i = 0; i < t->index; ++i) {\n if (t->str[i] != t->str[i + diff]) {\n break;\n }\n }\n\n \/\/ if we successfully got through the previous loop then our current\n \/\/ index is good.\n if (i == t->index) {\n t->index++;\n break;\n }\n\n \/\/ otherwise we just try the next index\n } while (t->index);\n }\n }\n \/\/ unreachable\n return -1;\n}\n","avg_line_length":26.3128654971,"max_line_length":100,"alphanum_fraction":0.6048449828} {"size":44725,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/*\n * Copyright (c) 2020-2021, Linus Groh \n * Copyright (c) 2021, Andreas Kling \n *\n * SPDX-License-Identifier: BSD-2-Clause\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace JS {\n\n\/\/ 7.2.1 RequireObjectCoercible ( argument ), https:\/\/tc39.es\/ecma262\/#sec-requireobjectcoercible\nThrowCompletionOr require_object_coercible(GlobalObject& global_object, Value value)\n{\n auto& vm = global_object.vm();\n if (value.is_nullish())\n return vm.throw_completion(global_object, ErrorType::NotObjectCoercible, value.to_string_without_side_effects());\n return value;\n}\n\n\/\/ 7.3.13 Call ( F, V [ , argumentsList ] ), https:\/\/tc39.es\/ecma262\/#sec-call\nThrowCompletionOr call_impl(GlobalObject& global_object, Value function, Value this_value, Optional arguments_list)\n{\n auto& vm = global_object.vm();\n\n \/\/ 1. If argumentsList is not present, set argumentsList to a new empty List.\n if (!arguments_list.has_value())\n arguments_list = MarkedValueList { global_object.heap() };\n\n \/\/ 2. If IsCallable(F) is false, throw a TypeError exception.\n if (!function.is_function())\n return vm.throw_completion(global_object, ErrorType::NotAFunction, function.to_string_without_side_effects());\n\n \/\/ 3. Return ? F.[[Call]](V, argumentsList).\n return function.as_function().internal_call(this_value, move(*arguments_list));\n}\n\n\/\/ 7.3.14 Construct ( F [ , argumentsList [ , newTarget ] ] ), https:\/\/tc39.es\/ecma262\/#sec-construct\nThrowCompletionOr construct(GlobalObject& global_object, FunctionObject& function, Optional arguments_list, FunctionObject* new_target)\n{\n \/\/ 1. If newTarget is not present, set newTarget to F.\n if (!new_target)\n new_target = &function;\n\n \/\/ 2. If argumentsList is not present, set argumentsList to a new empty List.\n if (!arguments_list.has_value())\n arguments_list = MarkedValueList { global_object.heap() };\n\n \/\/ 3. Return ? F.[[Construct]](argumentsList, newTarget).\n return function.internal_construct(move(*arguments_list), *new_target);\n}\n\n\/\/ 7.3.18 LengthOfArrayLike ( obj ), https:\/\/tc39.es\/ecma262\/#sec-lengthofarraylike\nThrowCompletionOr length_of_array_like(GlobalObject& global_object, Object const& object)\n{\n auto& vm = global_object.vm();\n auto result = TRY(object.get(vm.names.length));\n auto length = result.to_length(global_object);\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n return length;\n}\n\n\/\/ 7.3.19 CreateListFromArrayLike ( obj [ , elementTypes ] ), https:\/\/tc39.es\/ecma262\/#sec-createlistfromarraylike\nThrowCompletionOr create_list_from_array_like(GlobalObject& global_object, Value value, Function(Value)> check_value)\n{\n auto& vm = global_object.vm();\n auto& heap = global_object.heap();\n\n \/\/ 1. If elementTypes is not present, set elementTypes to \u00ab Undefined, Null, Boolean, String, Symbol, Number, BigInt, Object \u00bb.\n\n \/\/ 2. If Type(obj) is not Object, throw a TypeError exception.\n if (!value.is_object())\n return vm.throw_completion(global_object, ErrorType::NotAnObject, value.to_string_without_side_effects());\n\n auto& array_like = value.as_object();\n\n \/\/ 3. Let len be ? LengthOfArrayLike(obj).\n auto length = TRY(length_of_array_like(global_object, array_like));\n\n \/\/ 4. Let list be a new empty List.\n auto list = MarkedValueList { heap };\n\n \/\/ 5. Let index be 0.\n \/\/ 6. Repeat, while index < len,\n for (size_t i = 0; i < length; ++i) {\n \/\/ a. Let indexName be ! ToString(\ud835\udd3d(index)).\n auto index_name = PropertyName { i };\n\n \/\/ b. Let next be ? Get(obj, indexName).\n auto next = TRY(array_like.get(index_name));\n\n \/\/ c. If Type(next) is not an element of elementTypes, throw a TypeError exception.\n if (check_value)\n TRY(check_value(next));\n\n \/\/ d. Append next as the last element of list.\n list.append(next);\n }\n\n \/\/ 7. Return list.\n return ThrowCompletionOr(move(list));\n}\n\n\/\/ 7.3.22 SpeciesConstructor ( O, defaultConstructor ), https:\/\/tc39.es\/ecma262\/#sec-speciesconstructor\nThrowCompletionOr species_constructor(GlobalObject& global_object, Object const& object, FunctionObject& default_constructor)\n{\n auto& vm = global_object.vm();\n\n \/\/ 1. Let C be ? Get(O, \"constructor\").\n auto constructor = TRY(object.get(vm.names.constructor));\n\n \/\/ 2. If C is undefined, return defaultConstructor.\n if (constructor.is_undefined())\n return &default_constructor;\n\n \/\/ 3. If Type(C) is not Object, throw a TypeError exception.\n if (!constructor.is_object())\n return vm.throw_completion(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());\n\n \/\/ 4. Let S be ? Get(C, @@species).\n auto species = TRY(constructor.as_object().get(*vm.well_known_symbol_species()));\n\n \/\/ 5. If S is either undefined or null, return defaultConstructor.\n if (species.is_nullish())\n return &default_constructor;\n\n \/\/ 6. If IsConstructor(S) is true, return S.\n if (species.is_constructor())\n return &species.as_function();\n\n \/\/ 7. Throw a TypeError exception.\n return vm.throw_completion(global_object, ErrorType::NotAConstructor, species.to_string_without_side_effects());\n}\n\n\/\/ 7.3.24 GetFunctionRealm ( obj ), https:\/\/tc39.es\/ecma262\/#sec-getfunctionrealm\nThrowCompletionOr get_function_realm(GlobalObject& global_object, FunctionObject const& function)\n{\n auto& vm = global_object.vm();\n\n \/\/ 1. Assert: ! IsCallable(obj) is true.\n\n \/\/ 2. If obj has a [[Realm]] internal slot, then\n if (function.realm()) {\n \/\/ a. Return obj.[[Realm]].\n return function.realm();\n }\n\n \/\/ 3. If obj is a bound function exotic object, then\n if (is(function)) {\n auto& bound_function = static_cast(function);\n\n \/\/ a. Let target be obj.[[BoundTargetFunction]].\n auto& target = bound_function.bound_target_function();\n\n \/\/ b. Return ? GetFunctionRealm(target).\n return get_function_realm(global_object, target);\n }\n\n \/\/ 4. If obj is a Proxy exotic object, then\n if (is(function)) {\n auto& proxy = static_cast(function);\n\n \/\/ a. If obj.[[ProxyHandler]] is null, throw a TypeError exception.\n if (proxy.is_revoked())\n return vm.throw_completion(global_object, ErrorType::ProxyRevoked);\n\n \/\/ b. Let proxyTarget be obj.[[ProxyTarget]].\n auto& proxy_target = proxy.target();\n\n \/\/ c. Return ? GetFunctionRealm(proxyTarget).\n VERIFY(proxy_target.is_function());\n return get_function_realm(global_object, static_cast(proxy_target));\n }\n\n \/\/ 5. Return the current Realm Record.\n return vm.current_realm();\n}\n\n\/\/ 10.1.6.2 IsCompatiblePropertyDescriptor ( Extensible, Desc, Current ), https:\/\/tc39.es\/ecma262\/#sec-iscompatiblepropertydescriptor\nbool is_compatible_property_descriptor(bool extensible, PropertyDescriptor const& descriptor, Optional const& current)\n{\n \/\/ 1. Return ValidateAndApplyPropertyDescriptor(undefined, undefined, Extensible, Desc, Current).\n return validate_and_apply_property_descriptor(nullptr, {}, extensible, descriptor, current);\n}\n\n\/\/ 10.1.6.3 ValidateAndApplyPropertyDescriptor ( O, P, extensible, Desc, current ), https:\/\/tc39.es\/ecma262\/#sec-validateandapplypropertydescriptor\nbool validate_and_apply_property_descriptor(Object* object, PropertyName const& property_name, bool extensible, PropertyDescriptor const& descriptor, Optional const& current)\n{\n \/\/ 1. Assert: If O is not undefined, then IsPropertyKey(P) is true.\n if (object)\n VERIFY(property_name.is_valid());\n\n \/\/ 2. If current is undefined, then\n if (!current.has_value()) {\n \/\/ a. If extensible is false, return false.\n if (!extensible)\n return false;\n\n \/\/ b. Assert: extensible is true.\n \/\/ c. If IsGenericDescriptor(Desc) is true or IsDataDescriptor(Desc) is true, then\n if (descriptor.is_generic_descriptor() || descriptor.is_data_descriptor()) {\n \/\/ i. If O is not undefined, create an own data property named P of object O whose [[Value]], [[Writable]],\n \/\/ [[Enumerable]], and [[Configurable]] attribute values are described by Desc.\n \/\/ If the value of an attribute field of Desc is absent, the attribute of the newly created property is set\n \/\/ to its default value.\n if (object) {\n auto value = descriptor.value.value_or(js_undefined());\n object->storage_set(property_name, { value, descriptor.attributes() });\n }\n }\n \/\/ d. Else,\n else {\n \/\/ i. Assert: ! IsAccessorDescriptor(Desc) is true.\n VERIFY(descriptor.is_accessor_descriptor());\n\n \/\/ ii. If O is not undefined, create an own accessor property named P of object O whose [[Get]], [[Set]],\n \/\/ [[Enumerable]], and [[Configurable]] attribute values are described by Desc.\n \/\/ If the value of an attribute field of Desc is absent, the attribute of the newly created property is set\n \/\/ to its default value.\n if (object) {\n auto accessor = Accessor::create(object->vm(), descriptor.get.value_or(nullptr), descriptor.set.value_or(nullptr));\n object->storage_set(property_name, { accessor, descriptor.attributes() });\n }\n }\n \/\/ e. Return true.\n return true;\n }\n\n \/\/ 3. If every field in Desc is absent, return true.\n if (descriptor.is_empty())\n return true;\n\n \/\/ 4. If current.[[Configurable]] is false, then\n if (!*current->configurable) {\n \/\/ a. If Desc.[[Configurable]] is present and its value is true, return false.\n if (descriptor.configurable.has_value() && *descriptor.configurable)\n return false;\n\n \/\/ b. If Desc.[[Enumerable]] is present and ! SameValue(Desc.[[Enumerable]], current.[[Enumerable]]) is false, return false.\n if (descriptor.enumerable.has_value() && *descriptor.enumerable != *current->enumerable)\n return false;\n }\n\n \/\/ 5. If ! IsGenericDescriptor(Desc) is true, then\n if (descriptor.is_generic_descriptor()) {\n \/\/ a. NOTE: No further validation is required.\n }\n \/\/ 6. Else if ! SameValue(! IsDataDescriptor(current), ! IsDataDescriptor(Desc)) is false, then\n else if (current->is_data_descriptor() != descriptor.is_data_descriptor()) {\n \/\/ a. If current.[[Configurable]] is false, return false.\n if (!*current->configurable)\n return false;\n\n \/\/ b. If IsDataDescriptor(current) is true, then\n if (current->is_data_descriptor()) {\n \/\/ If O is not undefined, convert the property named P of object O from a data property to an accessor property.\n \/\/ Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and\n \/\/ set the rest of the property's attributes to their default values.\n if (object) {\n auto accessor = Accessor::create(object->vm(), nullptr, nullptr);\n object->storage_set(property_name, { accessor, current->attributes() });\n }\n }\n \/\/ c. Else,\n else {\n \/\/ If O is not undefined, convert the property named P of object O from an accessor property to a data property.\n \/\/ Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and\n \/\/ set the rest of the property's attributes to their default values.\n if (object) {\n auto value = js_undefined();\n object->storage_set(property_name, { value, current->attributes() });\n }\n }\n }\n \/\/ 7. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true, then\n else if (current->is_data_descriptor() && descriptor.is_data_descriptor()) {\n \/\/ a. If current.[[Configurable]] is false and current.[[Writable]] is false, then\n if (!*current->configurable && !*current->writable) {\n \/\/ i. If Desc.[[Writable]] is present and Desc.[[Writable]] is true, return false.\n if (descriptor.writable.has_value() && *descriptor.writable)\n return false;\n\n \/\/ ii. If Desc.[[Value]] is present and SameValue(Desc.[[Value]], current.[[Value]]) is false, return false.\n if (descriptor.value.has_value() && !same_value(*descriptor.value, *current->value))\n return false;\n\n \/\/ iii. Return true.\n return true;\n }\n }\n \/\/ 8. Else,\n else {\n \/\/ a. Assert: ! IsAccessorDescriptor(current) and ! IsAccessorDescriptor(Desc) are both true.\n VERIFY(current->is_accessor_descriptor());\n VERIFY(descriptor.is_accessor_descriptor());\n\n \/\/ b. If current.[[Configurable]] is false, then\n if (!*current->configurable) {\n \/\/ i. If Desc.[[Set]] is present and SameValue(Desc.[[Set]], current.[[Set]]) is false, return false.\n if (descriptor.set.has_value() && *descriptor.set != *current->set)\n return false;\n\n \/\/ ii. If Desc.[[Get]] is present and SameValue(Desc.[[Get]], current.[[Get]]) is false, return false.\n if (descriptor.get.has_value() && *descriptor.get != *current->get)\n return false;\n\n \/\/ iii. Return true.\n return true;\n }\n }\n\n \/\/ 9. If O is not undefined, then\n if (object) {\n \/\/ a. For each field of Desc that is present, set the corresponding attribute of the property named P of object O to the value of the field.\n Value value;\n if (descriptor.is_accessor_descriptor() || (current->is_accessor_descriptor() && !descriptor.is_data_descriptor())) {\n auto* getter = descriptor.get.value_or(current->get.value_or(nullptr));\n auto* setter = descriptor.set.value_or(current->set.value_or(nullptr));\n value = Accessor::create(object->vm(), getter, setter);\n } else {\n value = descriptor.value.value_or(current->value.value_or({}));\n }\n PropertyAttributes attributes;\n attributes.set_writable(descriptor.writable.value_or(current->writable.value_or(false)));\n attributes.set_enumerable(descriptor.enumerable.value_or(current->enumerable.value_or(false)));\n attributes.set_configurable(descriptor.configurable.value_or(current->configurable.value_or(false)));\n object->storage_set(property_name, { value, attributes });\n }\n\n \/\/ 10. Return true.\n return true;\n}\n\n\/\/ 10.1.14 GetPrototypeFromConstructor ( constructor, intrinsicDefaultProto ), https:\/\/tc39.es\/ecma262\/#sec-getprototypefromconstructor\nThrowCompletionOr get_prototype_from_constructor(GlobalObject& global_object, FunctionObject const& constructor, Object* (GlobalObject::*intrinsic_default_prototype)())\n{\n auto& vm = global_object.vm();\n\n \/\/ 1. Assert: intrinsicDefaultProto is this specification's name of an intrinsic object. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.\n\n \/\/ 2. Let proto be ? Get(constructor, \"prototype\").\n auto prototype = TRY(constructor.get(vm.names.prototype));\n\n \/\/ 3. If Type(proto) is not Object, then\n if (!prototype.is_object()) {\n \/\/ a. Let realm be ? GetFunctionRealm(constructor).\n auto* realm = TRY(get_function_realm(global_object, constructor));\n\n \/\/ b. Set proto to realm's intrinsic object named intrinsicDefaultProto.\n prototype = (realm->global_object().*intrinsic_default_prototype)();\n }\n\n \/\/ 4. Return proto.\n return &prototype.as_object();\n}\n\n\/\/ 9.1.2.2 NewDeclarativeEnvironment ( E ), https:\/\/tc39.es\/ecma262\/#sec-newdeclarativeenvironment\nDeclarativeEnvironment* new_declarative_environment(Environment& environment)\n{\n auto& global_object = environment.global_object();\n return global_object.heap().allocate(global_object, &environment);\n}\n\n\/\/ 9.1.2.3 NewObjectEnvironment ( O, W, E ), https:\/\/tc39.es\/ecma262\/#sec-newobjectenvironment\nObjectEnvironment* new_object_environment(Object& object, bool is_with_environment, Environment* environment)\n{\n auto& global_object = object.global_object();\n return global_object.heap().allocate(global_object, object, is_with_environment ? ObjectEnvironment::IsWithEnvironment::Yes : ObjectEnvironment::IsWithEnvironment::No, environment);\n}\n\n\/\/ 9.1.2.4 NewFunctionEnvironment ( F, newTarget ), https:\/\/tc39.es\/ecma262\/#sec-newfunctionenvironment\nFunctionEnvironment* new_function_environment(ECMAScriptFunctionObject& function, Object* new_target)\n{\n auto& global_object = function.global_object();\n\n \/\/ 1. Let env be a new function Environment Record containing no bindings.\n auto* env = global_object.heap().allocate(global_object, function.environment());\n\n \/\/ 2. Set env.[[FunctionObject]] to F.\n env->set_function_object(function);\n\n \/\/ 3. If F.[[ThisMode]] is lexical, set env.[[ThisBindingStatus]] to lexical.\n if (function.this_mode() == ECMAScriptFunctionObject::ThisMode::Lexical)\n env->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Lexical);\n \/\/ 4. Else, set env.[[ThisBindingStatus]] to uninitialized.\n else\n env->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Uninitialized);\n\n \/\/ 5. Set env.[[NewTarget]] to newTarget.\n env->set_new_target(new_target ?: js_undefined());\n\n \/\/ 6. Set env.[[OuterEnv]] to F.[[Environment]].\n \/\/ NOTE: Done in step 1 via the FunctionEnvironment constructor.\n\n \/\/ 7. Return env.\n return env;\n}\n\n\/\/ 9.4.3 GetThisEnvironment ( ), https:\/\/tc39.es\/ecma262\/#sec-getthisenvironment\nEnvironment& get_this_environment(VM& vm)\n{\n for (auto* env = vm.lexical_environment(); env; env = env->outer_environment()) {\n if (env->has_this_binding())\n return *env;\n }\n VERIFY_NOT_REACHED();\n}\n\n\/\/ 13.3.7.2 GetSuperConstructor ( ), https:\/\/tc39.es\/ecma262\/#sec-getsuperconstructor\nObject* get_super_constructor(VM& vm)\n{\n \/\/ 1. Let envRec be GetThisEnvironment().\n auto& env = get_this_environment(vm);\n\n \/\/ 2. Assert: envRec is a function Environment Record.\n \/\/ 3. Let activeFunction be envRec.[[FunctionObject]].\n \/\/ 4. Assert: activeFunction is an ECMAScript function object.\n auto& active_function = verify_cast(env).function_object();\n\n \/\/ 5. Let superConstructor be ! activeFunction.[[GetPrototypeOf]]().\n auto* super_constructor = MUST(active_function.internal_get_prototype_of());\n\n \/\/ 6. Return superConstructor.\n return super_constructor;\n}\n\n\/\/ 13.3.7.3 MakeSuperPropertyReference ( actualThis, propertyKey, strict ), https:\/\/tc39.es\/ecma262\/#sec-makesuperpropertyreference\nThrowCompletionOr make_super_property_reference(GlobalObject& global_object, Value actual_this, StringOrSymbol const& property_key, bool strict)\n{\n auto& vm = global_object.vm();\n \/\/ 1. Let env be GetThisEnvironment().\n auto& env = verify_cast(get_this_environment(vm));\n \/\/ 2. Assert: env.HasSuperBinding() is true.\n VERIFY(env.has_super_binding());\n \/\/ 3. Let baseValue be ? env.GetSuperBase().\n auto base_value = TRY(env.get_super_base());\n \/\/ 4. Let bv be ? RequireObjectCoercible(baseValue).\n auto bv = TRY(require_object_coercible(global_object, base_value));\n \/\/ 5. Return the Reference Record { [[Base]]: bv, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.\n \/\/ 6. NOTE: This returns a Super Reference Record.\n return Reference { bv, property_key, actual_this, strict };\n}\n\n\/\/ 19.2.1.1 PerformEval ( x, callerRealm, strictCaller, direct ), https:\/\/tc39.es\/ecma262\/#sec-performeval\nThrowCompletionOr perform_eval(Value x, GlobalObject& caller_realm, CallerMode strict_caller, EvalMode direct)\n{\n VERIFY(direct == EvalMode::Direct || strict_caller == CallerMode::NonStrict);\n if (!x.is_string())\n return x;\n\n auto& vm = caller_realm.vm();\n auto& eval_realm = vm.running_execution_context().realm;\n\n auto& code_string = x.as_string();\n Parser parser { Lexer { code_string.string() } };\n auto program = parser.parse_program(strict_caller == CallerMode::Strict);\n\n if (parser.has_errors()) {\n auto& error = parser.errors()[0];\n return vm.throw_completion(caller_realm, error.to_string());\n }\n\n auto strict_eval = strict_caller == CallerMode::Strict;\n if (program->is_strict_mode())\n strict_eval = true;\n\n auto& running_context = vm.running_execution_context();\n\n Environment* lexical_environment;\n Environment* variable_environment;\n if (direct == EvalMode::Direct) {\n lexical_environment = new_declarative_environment(*running_context.lexical_environment);\n variable_environment = running_context.variable_environment;\n } else {\n lexical_environment = new_declarative_environment(eval_realm->global_environment());\n variable_environment = &eval_realm->global_environment();\n }\n\n if (strict_eval)\n variable_environment = lexical_environment;\n\n if (direct == EvalMode::Direct && !strict_eval) {\n \/\/ NOTE: Non-strict direct eval() forces us to deoptimize variable accesses.\n \/\/ Mark the variable environment chain as screwed since we will not be able\n \/\/ to rely on cached environment coordinates from this point on.\n variable_environment->set_permanently_screwed_by_eval();\n }\n\n \/\/ 18. If runningContext is not already suspended, suspend runningContext.\n \/\/ FIXME: We don't have this concept yet.\n\n ExecutionContext eval_context(vm.heap());\n eval_context.realm = eval_realm;\n eval_context.variable_environment = variable_environment;\n eval_context.lexical_environment = lexical_environment;\n vm.push_execution_context(eval_context, eval_realm->global_object());\n\n ScopeGuard pop_guard = [&] {\n vm.pop_execution_context();\n };\n\n TRY(eval_declaration_instantiation(vm, eval_realm->global_object(), program, variable_environment, lexical_environment, strict_eval));\n\n auto& interpreter = vm.interpreter();\n TemporaryChange scope_change_strict(vm.running_execution_context().is_strict_mode, strict_eval);\n \/\/ FIXME: We need to use evaluate_statements() here because Program::execute() calls global_declaration_instantiation() when it shouldn't\n auto eval_result = program->evaluate_statements(interpreter, caller_realm);\n\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n else\n return eval_result.value_or(js_undefined());\n}\n\n\/\/ 19.2.1.3 EvalDeclarationInstantiation ( body, varEnv, lexEnv, privateEnv, strict ), https:\/\/tc39.es\/ecma262\/#sec-evaldeclarationinstantiation\nThrowCompletionOr eval_declaration_instantiation(VM& vm, GlobalObject& global_object, Program const& program, Environment* variable_environment, Environment* lexical_environment, bool strict)\n{\n \/\/ FIXME: I'm not sure if the global object is correct here. And this is quite a crucial spot!\n GlobalEnvironment* global_var_environment = variable_environment->is_global_environment() ? static_cast(variable_environment) : nullptr;\n\n if (!strict) {\n if (global_var_environment) {\n program.for_each_var_declared_name([&](auto const& name) {\n if (global_var_environment->has_lexical_declaration(name)) {\n vm.throw_exception(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, \"Var already declared lexically\");\n return IterationDecision::Break;\n }\n return IterationDecision::Continue;\n });\n }\n\n auto* this_environment = lexical_environment;\n while (this_environment != variable_environment) {\n if (!is(*this_environment)) {\n program.for_each_var_declared_name([&](auto const& name) {\n if (MUST(this_environment->has_binding(name))) {\n vm.throw_exception(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, \"Var already declared lexically\");\n return IterationDecision::Break;\n }\n \/\/ FIXME: NOTE: Annex B.3.4 defines alternate semantics for the above step.\n \/\/ In particular it only throw the syntax error if it is not an environment from a catchclause.\n return IterationDecision::Continue;\n });\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n }\n\n this_environment = this_environment->outer_environment();\n VERIFY(this_environment);\n }\n }\n\n HashTable declared_function_names;\n Vector functions_to_initialize;\n program.for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {\n if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)\n return IterationDecision::Continue;\n\n if (global_var_environment) {\n auto function_definable = global_var_environment->can_declare_global_function(function.name());\n if (vm.exception())\n return IterationDecision::Break;\n if (!function_definable) {\n vm.throw_exception(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, \"Cannot define global function\");\n return IterationDecision::Break;\n }\n }\n functions_to_initialize.append(function);\n return IterationDecision::Continue;\n });\n\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n\n if (!strict) {\n \/\/ The spec here uses 'declaredVarNames' but that has not been declared yet.\n HashTable hoisted_functions;\n program.for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {\n auto& function_name = function_declaration.name();\n auto* this_environment = lexical_environment;\n\n while (this_environment != variable_environment) {\n if (!is(*this_environment) && MUST(this_environment->has_binding(function_name)))\n return IterationDecision::Continue;\n\n this_environment = this_environment->outer_environment();\n VERIFY(this_environment);\n }\n\n if (global_var_environment) {\n if (global_var_environment->has_lexical_declaration(function_name))\n return IterationDecision::Continue;\n auto var_definable = global_var_environment->can_declare_global_var(function_name);\n if (vm.exception())\n return IterationDecision::Break;\n if (!var_definable)\n return IterationDecision::Continue;\n }\n\n if (!declared_function_names.contains(function_name) && !hoisted_functions.contains(function_name)) {\n if (global_var_environment) {\n global_var_environment->create_global_var_binding(function_name, true);\n if (vm.exception())\n return IterationDecision::Break;\n } else {\n if (!MUST(variable_environment->has_binding(function_name))) {\n MUST(variable_environment->create_mutable_binding(global_object, function_name, true));\n MUST(variable_environment->initialize_binding(global_object, function_name, js_undefined()));\n }\n }\n\n hoisted_functions.set(function_name);\n }\n\n function_declaration.set_should_do_additional_annexB_steps();\n\n return IterationDecision::Continue;\n });\n\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n }\n\n HashTable declared_var_names;\n\n program.for_each_var_scoped_variable_declaration([&](VariableDeclaration const& declaration) {\n declaration.for_each_bound_name([&](auto const& name) {\n if (!declared_function_names.contains(name)) {\n if (global_var_environment) {\n auto variable_definable = global_var_environment->can_declare_global_var(name);\n if (vm.exception())\n return IterationDecision::Break;\n if (!variable_definable) {\n vm.throw_exception(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, \"Cannot define global var\");\n return IterationDecision::Break;\n }\n }\n declared_var_names.set(name);\n }\n return IterationDecision::Continue;\n });\n if (vm.exception())\n return IterationDecision::Break;\n return IterationDecision::Continue;\n });\n\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n\n \/\/ 14. NOTE: No abnormal terminations occur after this algorithm step unless varEnv is a global Environment Record and the global object is a Proxy exotic object.\n\n program.for_each_lexically_scoped_declaration([&](Declaration const& declaration) {\n declaration.for_each_bound_name([&](auto const& name) {\n if (declaration.is_constant_declaration())\n (void)lexical_environment->create_immutable_binding(global_object, name, true);\n else\n (void)lexical_environment->create_mutable_binding(global_object, name, false);\n if (vm.exception())\n return IterationDecision::Break;\n return IterationDecision::Continue;\n });\n if (vm.exception())\n return IterationDecision::Break;\n return IterationDecision::Continue;\n });\n\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n\n for (auto& declaration : functions_to_initialize) {\n auto* function = ECMAScriptFunctionObject::create(global_object, declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), lexical_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object());\n if (global_var_environment) {\n global_var_environment->create_global_function_binding(declaration.name(), function, true);\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n } else {\n auto binding_exists = MUST(variable_environment->has_binding(declaration.name()));\n\n if (!binding_exists) {\n TRY(variable_environment->create_mutable_binding(global_object, declaration.name(), true));\n TRY(variable_environment->initialize_binding(global_object, declaration.name(), function));\n } else {\n TRY(variable_environment->set_mutable_binding(global_object, declaration.name(), function, false));\n }\n }\n }\n\n for (auto& var_name : declared_var_names) {\n if (global_var_environment) {\n global_var_environment->create_global_var_binding(var_name, true);\n if (auto* exception = vm.exception())\n return throw_completion(exception->value());\n } else {\n auto binding_exists = MUST(variable_environment->has_binding(var_name));\n\n if (!binding_exists) {\n TRY(variable_environment->create_mutable_binding(global_object, var_name, true));\n TRY(variable_environment->initialize_binding(global_object, var_name, js_undefined()));\n }\n }\n }\n\n return {};\n}\n\n\/\/ 10.4.4.6 CreateUnmappedArgumentsObject ( argumentsList ), https:\/\/tc39.es\/ecma262\/#sec-createunmappedargumentsobject\nObject* create_unmapped_arguments_object(GlobalObject& global_object, Span arguments)\n{\n auto& vm = global_object.vm();\n\n \/\/ 1. Let len be the number of elements in argumentsList.\n auto length = arguments.size();\n\n \/\/ 2. Let obj be ! OrdinaryObjectCreate(%Object.prototype%, \u00ab [[ParameterMap]] \u00bb).\n \/\/ 3. Set obj.[[ParameterMap]] to undefined.\n auto* object = Object::create(global_object, global_object.object_prototype());\n object->set_has_parameter_map();\n\n \/\/ 4. Perform DefinePropertyOrThrow(obj, \"length\", PropertyDescriptor { [[Value]]: \ud835\udd3d(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).\n MUST(object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true }));\n\n \/\/ 5. Let index be 0.\n \/\/ 6. Repeat, while index < len,\n for (size_t index = 0; index < length; ++index) {\n \/\/ a. Let val be argumentsList[index].\n auto value = arguments[index];\n\n \/\/ b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(\ud835\udd3d(index)), val).\n MUST(object->create_data_property_or_throw(index, value));\n\n \/\/ c. Set index to index + 1.\n }\n\n \/\/ 7. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).\n auto* array_prototype_values = global_object.array_prototype_values_function();\n MUST(object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true }));\n\n \/\/ 8. Perform ! DefinePropertyOrThrow(obj, \"callee\", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false }).\n auto* throw_type_error = global_object.throw_type_error_function();\n MUST(object->define_property_or_throw(vm.names.callee, { .get = throw_type_error, .set = throw_type_error, .enumerable = false, .configurable = false }));\n\n \/\/ 9. Return obj.\n return object;\n}\n\n\/\/ 10.4.4.7 CreateMappedArgumentsObject ( func, formals, argumentsList, env ), https:\/\/tc39.es\/ecma262\/#sec-createmappedargumentsobject\nObject* create_mapped_arguments_object(GlobalObject& global_object, FunctionObject& function, Vector const& formals, Span arguments, Environment& environment)\n{\n auto& vm = global_object.vm();\n\n \/\/ 1. Assert: formals does not contain a rest parameter, any binding patterns, or any initializers. It may contain duplicate identifiers.\n\n \/\/ 2. Let len be the number of elements in argumentsList.\n VERIFY(arguments.size() <= NumericLimits::max());\n i32 length = static_cast(arguments.size());\n\n \/\/ 3. Let obj be ! MakeBasicObject(\u00ab [[Prototype]], [[Extensible]], [[ParameterMap]] \u00bb).\n \/\/ 4. Set obj.[[GetOwnProperty]] as specified in 10.4.4.1.\n \/\/ 5. Set obj.[[DefineOwnProperty]] as specified in 10.4.4.2.\n \/\/ 6. Set obj.[[Get]] as specified in 10.4.4.3.\n \/\/ 7. Set obj.[[Set]] as specified in 10.4.4.4.\n \/\/ 8. Set obj.[[Delete]] as specified in 10.4.4.5.\n \/\/ 9. Set obj.[[Prototype]] to %Object.prototype%.\n auto* object = vm.heap().allocate(global_object, global_object, environment);\n VERIFY(!vm.exception());\n\n \/\/ 14. Let index be 0.\n \/\/ 15. Repeat, while index < len,\n for (i32 index = 0; index < length; ++index) {\n \/\/ a. Let val be argumentsList[index].\n auto value = arguments[index];\n\n \/\/ b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(\ud835\udd3d(index)), val).\n MUST(object->create_data_property_or_throw(index, value));\n\n \/\/ c. Set index to index + 1.\n }\n\n \/\/ 16. Perform ! DefinePropertyOrThrow(obj, \"length\", PropertyDescriptor { [[Value]]: \ud835\udd3d(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).\n MUST(object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true }));\n\n \/\/ 17. Let mappedNames be a new empty List.\n HashTable mapped_names;\n\n \/\/ 18. Set index to numberOfParameters - 1.\n \/\/ 19. Repeat, while index \u2265 0,\n VERIFY(formals.size() <= NumericLimits::max());\n for (i32 index = static_cast(formals.size()) - 1; index >= 0; --index) {\n \/\/ a. Let name be parameterNames[index].\n auto const& name = formals[index].binding.get();\n\n \/\/ b. If name is not an element of mappedNames, then\n if (mapped_names.contains(name))\n continue;\n\n \/\/ i. Add name as an element of the list mappedNames.\n mapped_names.set(name);\n\n \/\/ ii. If index < len, then\n if (index < length) {\n \/\/ 1. Let g be MakeArgGetter(name, env).\n \/\/ 2. Let p be MakeArgSetter(name, env).\n \/\/ 3. Perform map.[[DefineOwnProperty]](! ToString(\ud835\udd3d(index)), PropertyDescriptor { [[Set]]: p, [[Get]]: g, [[Enumerable]]: false, [[Configurable]]: true }).\n object->parameter_map().define_native_accessor(\n PropertyName { index },\n [&environment, name](VM&, GlobalObject& global_object_getter) -> Value {\n return MUST(environment.get_binding_value(global_object_getter, name, false));\n },\n [&environment, name](VM& vm, GlobalObject& global_object_setter) {\n MUST(environment.set_mutable_binding(global_object_setter, name, vm.argument(0), false));\n return js_undefined();\n },\n Attribute::Configurable);\n }\n }\n\n \/\/ 20. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).\n auto* array_prototype_values = global_object.array_prototype_values_function();\n MUST(object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true }));\n\n \/\/ 21. Perform ! DefinePropertyOrThrow(obj, \"callee\", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).\n MUST(object->define_property_or_throw(vm.names.callee, { .value = &function, .writable = true, .enumerable = false, .configurable = true }));\n\n \/\/ 22. Return obj.\n return object;\n}\n\n\/\/ 7.1.21 CanonicalNumericIndexString ( argument ), https:\/\/tc39.es\/ecma262\/#sec-canonicalnumericindexstring\nValue canonical_numeric_index_string(GlobalObject& global_object, PropertyName const& property_name)\n{\n \/\/ NOTE: If the property name is a number type (An implementation-defined optimized\n \/\/ property key type), it can be treated as a string property that has already been\n \/\/ converted successfully into a canonical numeric index.\n\n VERIFY(property_name.is_string() || property_name.is_number());\n\n if (property_name.is_number())\n return Value(property_name.as_number());\n\n \/\/ 1. Assert: Type(argument) is String.\n auto argument = Value(js_string(global_object.vm(), property_name.as_string()));\n\n \/\/ 2. If argument is \"-0\", return -0\ud835\udd3d.\n if (argument.as_string().string() == \"-0\")\n return Value(-0.0);\n\n \/\/ 3. Let n be ! ToNumber(argument).\n auto n = argument.to_number(global_object);\n\n \/\/ 4. If SameValue(! ToString(n), argument) is false, return undefined.\n if (!same_value(MUST(n.to_primitive_string(global_object)), argument))\n return js_undefined();\n\n \/\/ 5. Return n.\n return n;\n}\n\n\/\/ 22.1.3.17.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacement ), https:\/\/tc39.es\/ecma262\/#sec-getsubstitution\nThrowCompletionOr get_substitution(GlobalObject& global_object, Utf16View const& matched, Utf16View const& str, size_t position, Span captures, Value named_captures, Value replacement)\n{\n auto replace_string = TRY(replacement.to_utf16_string(global_object));\n auto replace_view = replace_string.view();\n\n StringBuilder result;\n\n for (size_t i = 0; i < replace_view.length_in_code_units(); ++i) {\n u16 curr = replace_view.code_unit_at(i);\n\n if ((curr != '$') || (i + 1 >= replace_view.length_in_code_units())) {\n result.append(curr);\n continue;\n }\n\n u16 next = replace_view.code_unit_at(i + 1);\n\n if (next == '$') {\n result.append('$');\n ++i;\n } else if (next == '&') {\n result.append(matched);\n ++i;\n } else if (next == '`') {\n auto substring = str.substring_view(0, position);\n result.append(substring);\n ++i;\n } else if (next == '\\'') {\n auto tail_pos = position + matched.length_in_code_units();\n if (tail_pos < str.length_in_code_units()) {\n auto substring = str.substring_view(tail_pos);\n result.append(substring);\n }\n ++i;\n } else if (is_ascii_digit(next)) {\n bool is_two_digits = (i + 2 < replace_view.length_in_code_units()) && is_ascii_digit(replace_view.code_unit_at(i + 2));\n\n auto capture_postition_string = replace_view.substring_view(i + 1, is_two_digits ? 2 : 1).to_utf8();\n auto capture_position = capture_postition_string.to_uint();\n\n if (capture_position.has_value() && (*capture_position > 0) && (*capture_position <= captures.size())) {\n auto& value = captures[*capture_position - 1];\n\n if (!value.is_undefined()) {\n auto value_string = TRY(value.to_string(global_object));\n result.append(value_string);\n }\n\n i += is_two_digits ? 2 : 1;\n } else {\n result.append(curr);\n }\n } else if (next == '<') {\n auto start_position = i + 2;\n Optional end_position;\n\n for (size_t j = start_position; j < replace_view.length_in_code_units(); ++j) {\n if (replace_view.code_unit_at(j) == '>') {\n end_position = j;\n break;\n }\n }\n\n if (named_captures.is_undefined() || !end_position.has_value()) {\n result.append(curr);\n } else {\n auto group_name_view = replace_view.substring_view(start_position, *end_position - start_position);\n auto group_name = group_name_view.to_utf8(Utf16View::AllowInvalidCodeUnits::Yes);\n\n auto capture = TRY(named_captures.as_object().get(group_name));\n\n if (!capture.is_undefined()) {\n auto capture_string = TRY(capture.to_string(global_object));\n result.append(capture_string);\n }\n\n i = *end_position;\n }\n } else {\n result.append(curr);\n }\n }\n\n return result.build();\n}\n\n}\n","avg_line_length":46.0607621009,"max_line_length":284,"alphanum_fraction":0.6619340414} {"size":22476,"ext":"cc","lang":"C++","max_stars_count":1.0,"content":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/bookmarks\/bookmark_editor_view.h\"\n\n#include \n#include \n\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"base\/logging.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_model_factory.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/bookmarks\/bookmark_utils.h\"\n#include \"chrome\/browser\/ui\/bookmarks\/bookmark_utils_desktop.h\"\n#include \"chrome\/browser\/ui\/browser_dialogs.h\"\n#include \"chrome\/browser\/ui\/views\/chrome_layout_provider.h\"\n#include \"chrome\/grit\/generated_resources.h\"\n#include \"chrome\/grit\/locale_settings.h\"\n#include \"components\/bookmarks\/browser\/bookmark_model.h\"\n#include \"components\/bookmarks\/browser\/bookmark_utils.h\"\n#include \"components\/constrained_window\/constrained_window_views.h\"\n#include \"components\/history\/core\/browser\/history_service.h\"\n#include \"components\/strings\/grit\/components_strings.h\"\n#include \"components\/url_formatter\/url_fixer.h\"\n#include \"components\/user_prefs\/user_prefs.h\"\n#include \"ui\/accessibility\/ax_node_data.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/metadata\/metadata_impl_macros.h\"\n#include \"ui\/events\/event.h\"\n#include \"ui\/views\/background.h\"\n#include \"ui\/views\/controls\/button\/md_text_button.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/controls\/menu\/menu_runner.h\"\n#include \"ui\/views\/controls\/scroll_view.h\"\n#include \"ui\/views\/controls\/textfield\/textfield.h\"\n#include \"ui\/views\/controls\/tree\/tree_view.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"url\/gurl.h\"\n\nusing bookmarks::BookmarkExpandedStateTracker;\nusing bookmarks::BookmarkModel;\nusing bookmarks::BookmarkNode;\n\nBookmarkEditorView::BookmarkEditorView(\n Profile* profile,\n const BookmarkNode* parent,\n const EditDetails& details,\n BookmarkEditor::Configuration configuration)\n : profile_(profile),\n parent_(parent),\n details_(details),\n bb_model_(BookmarkModelFactory::GetForBrowserContext(profile)),\n show_tree_(configuration == SHOW_TREE) {\n DCHECK(profile);\n DCHECK(bb_model_);\n DCHECK(bb_model_->client()->CanBeEditedByUser(parent));\n SetCanResize(true);\n SetModalType(ui::MODAL_TYPE_WINDOW);\n SetShowCloseButton(false);\n SetAcceptCallback(base::BindOnce(&BookmarkEditorView::ApplyEdits,\n base::Unretained(this), nullptr));\n SetTitle(details_.GetWindowTitleId());\n SetButtonLabel(ui::DIALOG_BUTTON_OK, l10n_util::GetStringUTF16(IDS_SAVE));\n if (show_tree_) {\n new_folder_button_ = SetExtraView(std::make_unique(\n base::BindRepeating(&BookmarkEditorView::NewFolderButtonPressed,\n base::Unretained(this)),\n l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NEW_FOLDER_BUTTON)));\n new_folder_button_->SetEnabled(bb_model_->loaded());\n }\n set_margins(ChromeLayoutProvider::Get()->GetDialogInsetsForContentType(\n views::DialogContentType::kControl, views::DialogContentType::kControl));\n Init();\n chrome::RecordDialogCreation(chrome::DialogIdentifier::BOOKMARK_EDITOR);\n}\n\nBookmarkEditorView::~BookmarkEditorView() {\n \/\/ The tree model is deleted before the view. Reset the model otherwise the\n \/\/ tree will reference a deleted model.\n if (tree_view_)\n tree_view_->SetModel(nullptr);\n bb_model_->RemoveObserver(this);\n}\n\nbool BookmarkEditorView::IsDialogButtonEnabled(ui::DialogButton button) const {\n if (button == ui::DIALOG_BUTTON_OK) {\n if (!bb_model_->loaded())\n return false;\n\n if (details_.GetNodeType() != BookmarkNode::FOLDER)\n return GetInputURL().is_valid();\n }\n return true;\n}\n\ngfx::Size BookmarkEditorView::CalculatePreferredSize() const {\n if (!show_tree_)\n return views::View::CalculatePreferredSize();\n\n return gfx::Size(views::Widget::GetLocalizedContentsSize(\n IDS_EDITBOOKMARK_DIALOG_WIDTH_CHARS,\n IDS_EDITBOOKMARK_DIALOG_HEIGHT_LINES));\n}\n\nvoid BookmarkEditorView::OnTreeViewSelectionChanged(\n views::TreeView* tree_view) {\n}\n\nbool BookmarkEditorView::CanEdit(views::TreeView* tree_view,\n ui::TreeModelNode* node) {\n \/\/ Only allow editting of children of the bookmark bar node and other node.\n EditorNode* bb_node = tree_model_->AsNode(node);\n return (bb_node->parent() && bb_node->parent()->parent());\n}\n\nvoid BookmarkEditorView::ContentsChanged(views::Textfield* sender,\n const std::u16string& new_contents) {\n UserInputChanged();\n}\n\nbool BookmarkEditorView::HandleKeyEvent(views::Textfield* sender,\n const ui::KeyEvent& key_event) {\n return false;\n}\n\nvoid BookmarkEditorView::GetAccessibleNodeData(ui::AXNodeData* node_data) {\n views::DialogDelegateView::GetAccessibleNodeData(node_data);\n node_data->SetName(l10n_util::GetStringUTF8(IDS_BOOKMARK_EDITOR_TITLE));\n}\n\nbool BookmarkEditorView::IsCommandIdChecked(int command_id) const {\n return false;\n}\n\nbool BookmarkEditorView::IsCommandIdEnabled(int command_id) const {\n switch (command_id) {\n case IDS_EDIT:\n case IDS_DELETE:\n return !running_menu_for_root_;\n case IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM:\n return true;\n default:\n NOTREACHED();\n return false;\n }\n}\n\nbool BookmarkEditorView::GetAcceleratorForCommandId(\n int command_id,\n ui::Accelerator* accelerator) const {\n return GetWidget()->GetAccelerator(command_id, accelerator);\n}\n\nvoid BookmarkEditorView::ExecuteCommand(int command_id, int event_flags) {\n DCHECK(tree_view_->GetActiveNode());\n if (command_id == IDS_EDIT) {\n tree_view_->StartEditing(tree_view_->GetActiveNode());\n } else if (command_id == IDS_DELETE) {\n ExecuteCommandDelete(base::BindOnce(&chrome::ConfirmDeleteBookmarkNode,\n GetWidget()->GetNativeWindow()));\n } else {\n DCHECK_EQ(IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM, command_id);\n NewFolder(tree_model_->AsNode(tree_view_->GetActiveNode()));\n }\n}\n\nvoid BookmarkEditorView::Show(gfx::NativeWindow parent) {\n constrained_window::CreateBrowserModalDialogViews(this, parent);\n UserInputChanged();\n if (show_tree_ && bb_model_->loaded())\n ExpandAndSelect();\n GetWidget()->Show();\n \/\/ Select all the text in the name Textfield.\n title_tf_->SelectAll(true);\n \/\/ Give focus to the name Textfield.\n title_tf_->RequestFocus();\n}\n\nvoid BookmarkEditorView::ShowContextMenuForViewImpl(\n views::View* source,\n const gfx::Point& point,\n ui::MenuSourceType source_type) {\n DCHECK_EQ(tree_view_, source);\n if (!tree_view_->GetActiveNode())\n return;\n running_menu_for_root_ =\n (tree_model_->GetParent(tree_view_->GetActiveNode()) ==\n tree_model_->GetRoot());\n\n context_menu_runner_ = std::make_unique(\n GetMenuModel(),\n views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU);\n\n context_menu_runner_->RunMenuAt(source->GetWidget()->GetTopLevelWidget(),\n nullptr, gfx::Rect(point, gfx::Size()),\n views::MenuAnchorPosition::kTopRight,\n source_type);\n}\n\nvoid BookmarkEditorView::BookmarkNodeMoved(BookmarkModel* model,\n const BookmarkNode* old_parent,\n size_t old_index,\n const BookmarkNode* new_parent,\n size_t new_index) {\n Reset();\n}\n\nvoid BookmarkEditorView::BookmarkNodeAdded(BookmarkModel* model,\n const BookmarkNode* parent,\n size_t index) {\n Reset();\n}\n\nvoid BookmarkEditorView::BookmarkNodeRemoved(\n BookmarkModel* model,\n const BookmarkNode* parent,\n size_t index,\n const BookmarkNode* node,\n const std::set& removed_urls) {\n if ((details_.type == EditDetails::EXISTING_NODE &&\n details_.existing_node->HasAncestor(node)) ||\n (parent_ && parent_->HasAncestor(node))) {\n \/\/ The node, or its parent was removed. Close the dialog.\n GetWidget()->Close();\n } else {\n Reset();\n }\n}\n\nvoid BookmarkEditorView::BookmarkAllUserNodesRemoved(\n BookmarkModel* model,\n const std::set& removed_urls) {\n Reset();\n}\n\nvoid BookmarkEditorView::BookmarkNodeChildrenReordered(\n BookmarkModel* model,\n const BookmarkNode* node) {\n Reset();\n}\n\nvoid BookmarkEditorView::Init() {\n bb_model_->AddObserver(this);\n\n std::u16string title;\n GURL url;\n if (details_.type == EditDetails::EXISTING_NODE) {\n title = details_.existing_node->GetTitle();\n url = details_.existing_node->url();\n } else if (details_.type == EditDetails::NEW_FOLDER) {\n title = l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NEW_FOLDER_NAME);\n } else if (details_.type == EditDetails::NEW_URL) {\n url = details_.url;\n title = details_.title;\n }\n auto title_tf = std::make_unique();\n title_tf->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_EDITOR_NAME_LABEL));\n title_tf->SetText(title);\n title_tf->set_controller(this);\n\n std::unique_ptr tree_view;\n if (show_tree_) {\n tree_view = std::make_unique();\n tree_view->SetRootShown(false);\n tree_view->set_context_menu_controller(this);\n }\n\n views::GridLayout* layout =\n SetLayoutManager(std::make_unique());\n ChromeLayoutProvider* provider = ChromeLayoutProvider::Get();\n\n const int labels_column_set_id = 0;\n const int single_column_view_set_id = 1;\n const int buttons_column_set_id = 2;\n\n using ColumnSize = views::GridLayout::ColumnSize;\n views::ColumnSet* column_set = layout->AddColumnSet(labels_column_set_id);\n column_set->AddColumn(\n provider->GetControlLabelGridAlignment(), views::GridLayout::CENTER,\n views::GridLayout::kFixedSize, ColumnSize::kUsePreferred, 0, 0);\n column_set->AddPaddingColumn(\n views::GridLayout::kFixedSize,\n provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_HORIZONTAL));\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::CENTER, 1.0,\n ColumnSize::kUsePreferred, 0, 0);\n\n column_set = layout->AddColumnSet(single_column_view_set_id);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1.0,\n ColumnSize::kUsePreferred, 0, 0);\n\n column_set = layout->AddColumnSet(buttons_column_set_id);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING,\n views::GridLayout::kFixedSize,\n ColumnSize::kUsePreferred, 0, 0);\n column_set->AddPaddingColumn(\n 1.0,\n provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_HORIZONTAL));\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING,\n views::GridLayout::kFixedSize,\n ColumnSize::kUsePreferred, 0, 0);\n column_set->AddPaddingColumn(\n views::GridLayout::kFixedSize,\n provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_HORIZONTAL));\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING,\n views::GridLayout::kFixedSize,\n ColumnSize::kUsePreferred, 0, 0);\n column_set->LinkColumnSizes({0, 2, 4});\n\n layout->StartRow(views::GridLayout::kFixedSize, labels_column_set_id);\n layout->AddView(std::make_unique(\n l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NAME_LABEL)));\n title_tf_ = layout->AddView(std::move(title_tf));\n\n if (details_.GetNodeType() != BookmarkNode::FOLDER) {\n auto url_tf = std::make_unique();\n url_tf->SetText(chrome::FormatBookmarkURLForDisplay(url));\n url_tf->set_controller(this);\n url_tf->SetAccessibleName(\n l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_EDITOR_URL_LABEL));\n url_tf->SetTextInputType(ui::TextInputType::TEXT_INPUT_TYPE_URL);\n\n layout->AddPaddingRow(\n views::GridLayout::kFixedSize,\n provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL));\n\n layout->StartRow(views::GridLayout::kFixedSize, labels_column_set_id);\n layout->AddView(std::make_unique(\n l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_URL_LABEL)));\n url_tf_ = layout->AddView(std::move(url_tf));\n }\n\n if (show_tree_) {\n layout->AddPaddingRow(\n views::GridLayout::kFixedSize,\n provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL));\n layout->StartRow(1.0, single_column_view_set_id);\n tree_view_ = tree_view.get();\n layout->AddView(\n views::TreeView::CreateScrollViewWithTree(std::move(tree_view)));\n }\n\n if (!show_tree_ || bb_model_->loaded())\n Reset();\n}\n\nvoid BookmarkEditorView::Reset() {\n if (!show_tree_) {\n if (parent())\n UserInputChanged();\n return;\n }\n\n if (new_folder_button_)\n new_folder_button_->SetEnabled(true);\n\n \/\/ Do this first, otherwise when we invoke SetModel with the real one\n \/\/ tree_view will try to invoke something on the model we just deleted.\n tree_view_->SetModel(nullptr);\n\n tree_model_ = std::make_unique(CreateRootNode());\n\n tree_view_->SetModel(tree_model_.get());\n tree_view_->SetController(this);\n\n context_menu_runner_.reset();\n\n if (parent())\n ExpandAndSelect();\n}\n\nGURL BookmarkEditorView::GetInputURL() const {\n if (details_.GetNodeType() == BookmarkNode::FOLDER)\n return GURL();\n return url_formatter::FixupURL(base::UTF16ToUTF8(url_tf_->GetText()),\n std::string());\n}\n\nvoid BookmarkEditorView::UserInputChanged() {\n if (details_.GetNodeType() != BookmarkNode::FOLDER) {\n const GURL url(GetInputURL());\n url_tf_->SetInvalid(!url.is_valid());\n }\n DialogModelChanged();\n}\n\nvoid BookmarkEditorView::NewFolderButtonPressed() {\n DCHECK(tree_view_->GetSelectedNode());\n NewFolder(tree_model_->AsNode(tree_view_->GetSelectedNode()));\n}\n\nvoid BookmarkEditorView::NewFolder(EditorNode* parent) {\n \/\/ Create a new entry parented to the given item.\n DCHECK(parent);\n tree_view_->StartEditing(AddNewFolder(parent));\n}\n\nBookmarkEditorView::EditorNode* BookmarkEditorView::AddNewFolder(\n EditorNode* parent) {\n return tree_model_->Add(\n parent,\n std::make_unique(\n l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NEW_FOLDER_NAME), 0));\n}\n\nvoid BookmarkEditorView::ExpandAndSelect() {\n BookmarkExpandedStateTracker::Nodes expanded_nodes =\n bb_model_->expanded_state_tracker()->GetExpandedNodes();\n for (auto i(expanded_nodes.begin()); i != expanded_nodes.end(); ++i) {\n EditorNode* editor_node =\n FindNodeWithID(tree_model_->GetRoot(), (*i)->id());\n if (editor_node)\n tree_view_->Expand(editor_node);\n }\n\n const BookmarkNode* to_select = parent_;\n if (details_.type == EditDetails::EXISTING_NODE)\n to_select = details_.existing_node->parent();\n int64_t folder_id_to_select = to_select->id();\n EditorNode* b_node =\n FindNodeWithID(tree_model_->GetRoot(), folder_id_to_select);\n if (!b_node)\n b_node = tree_model_->GetRoot()->children().front().get(); \/\/ Bookmark bar.\n\n tree_view_->SetSelectedNode(b_node);\n}\n\nstd::unique_ptr\nBookmarkEditorView::CreateRootNode() {\n std::unique_ptr root_node =\n std::make_unique(std::u16string(), 0);\n const BookmarkNode* bb_root_node = bb_model_->root_node();\n CreateNodes(bb_root_node, root_node.get());\n DCHECK_GE(root_node->children().size(), 2u);\n DCHECK_LE(root_node->children().size(), 4u);\n DCHECK_EQ(BookmarkNode::BOOKMARK_BAR, bb_root_node->children()[0]->type());\n DCHECK_EQ(BookmarkNode::OTHER_NODE, bb_root_node->children()[1]->type());\n if (root_node->children().size() >= 3)\n DCHECK_EQ(BookmarkNode::MOBILE, bb_root_node->children()[2]->type());\n return root_node;\n}\n\nvoid BookmarkEditorView::CreateNodes(const BookmarkNode* bb_node,\n BookmarkEditorView::EditorNode* b_node) {\n for (const auto& child_bb_node : bb_node->children()) {\n if (child_bb_node->IsVisible() && child_bb_node->is_folder() &&\n bb_model_->client()->CanBeEditedByUser(child_bb_node.get())) {\n EditorNode* new_b_node = b_node->Add(std::make_unique(\n child_bb_node->GetTitle(), child_bb_node->id()));\n CreateNodes(child_bb_node.get(), new_b_node);\n }\n }\n}\n\nBookmarkEditorView::EditorNode* BookmarkEditorView::FindNodeWithID(\n BookmarkEditorView::EditorNode* node,\n int64_t id) {\n if (node->value == id)\n return node;\n for (const auto& child : node->children()) {\n EditorNode* result = FindNodeWithID(child.get(), id);\n if (result)\n return result;\n }\n return nullptr;\n}\n\nvoid BookmarkEditorView::ApplyEdits(EditorNode* parent) {\n DCHECK(bb_model_->loaded());\n\n if (!parent) {\n if (tree_view_)\n tree_view_->CommitEdit();\n\n if (show_tree_) {\n parent = tree_model_->AsNode(tree_view_->GetSelectedNode());\n DCHECK(parent);\n }\n }\n\n \/\/ We're going to apply edits to the bookmark bar model, which will call us\n \/\/ back. Normally when a structural edit occurs we reset the tree model.\n \/\/ We don't want to do that here, so we remove ourselves as an observer.\n bb_model_->RemoveObserver(this);\n\n GURL new_url(GetInputURL());\n std::u16string new_title(title_tf_->GetText());\n\n if (!show_tree_) {\n BookmarkEditor::ApplyEditsWithNoFolderChange(\n bb_model_, parent_, details_, new_title, new_url);\n return;\n }\n\n \/\/ Create the new folders and update the titles.\n const BookmarkNode* new_parent = nullptr;\n ApplyNameChangesAndCreateNewFolders(\n bb_model_->root_node(), tree_model_->GetRoot(), parent, &new_parent);\n\n BookmarkEditor::ApplyEditsWithPossibleFolderChange(\n bb_model_, new_parent, details_, new_title, new_url);\n\n BookmarkExpandedStateTracker::Nodes expanded_nodes;\n UpdateExpandedNodes(tree_model_->GetRoot(), &expanded_nodes);\n bb_model_->expanded_state_tracker()->SetExpandedNodes(expanded_nodes);\n\n \/\/ Remove the folders that were removed. This has to be done after all the\n \/\/ other changes have been committed.\n bookmarks::DeleteBookmarkFolders(bb_model_, deletes_);\n}\n\nvoid BookmarkEditorView::ApplyNameChangesAndCreateNewFolders(\n const BookmarkNode* bb_node,\n BookmarkEditorView::EditorNode* b_node,\n BookmarkEditorView::EditorNode* parent_b_node,\n const BookmarkNode** parent_bb_node) {\n if (parent_b_node == b_node)\n *parent_bb_node = bb_node;\n for (const auto& child_b_node : b_node->children()) {\n const BookmarkNode* child_bb_node = nullptr;\n if (child_b_node->value == 0) {\n \/\/ New folder.\n child_bb_node = bb_model_->AddFolder(bb_node, bb_node->children().size(),\n child_b_node->GetTitle());\n child_b_node->value = child_bb_node->id();\n } else {\n \/\/ Existing node, reset the title (BookmarkModel ignores changes if the\n \/\/ title is the same).\n const auto i = std::find_if(\n bb_node->children().cbegin(), bb_node->children().cend(),\n [&child_b_node](const auto& node) {\n return node->is_folder() && node->id() == child_b_node->value;\n });\n DCHECK(i != bb_node->children().cend());\n child_bb_node = i->get();\n bb_model_->SetTitle(child_bb_node, child_b_node->GetTitle());\n }\n ApplyNameChangesAndCreateNewFolders(child_bb_node, child_b_node.get(),\n parent_b_node, parent_bb_node);\n }\n}\n\nvoid BookmarkEditorView::UpdateExpandedNodes(\n EditorNode* editor_node,\n BookmarkExpandedStateTracker::Nodes* expanded_nodes) {\n if (!tree_view_->IsExpanded(editor_node))\n return;\n\n \/\/ The root is 0.\n if (editor_node->value != 0) {\n expanded_nodes->insert(\n bookmarks::GetBookmarkNodeByID(bb_model_, editor_node->value));\n }\n\n for (const auto& child : editor_node->children())\n UpdateExpandedNodes(child.get(), expanded_nodes);\n}\n\nui::SimpleMenuModel* BookmarkEditorView::GetMenuModel() {\n if (!context_menu_model_.get()) {\n context_menu_model_ = std::make_unique(this);\n context_menu_model_->AddItemWithStringId(IDS_EDIT, IDS_EDIT);\n context_menu_model_->AddItemWithStringId(IDS_DELETE, IDS_DELETE);\n context_menu_model_->AddItemWithStringId(\n IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM,\n IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM);\n }\n return context_menu_model_.get();\n}\n\nvoid BookmarkEditorView::ExecuteCommandDelete(\n base::OnceCallback\n non_empty_folder_confirmation_cb) {\n EditorNode* node = tree_model_->AsNode(tree_view_->GetActiveNode());\n if (!node)\n return;\n const int64_t bookmark_node_id = node->value;\n if (bookmark_node_id != 0) {\n const BookmarkNode* b_node =\n bookmarks::GetBookmarkNodeByID(bb_model_, bookmark_node_id);\n if (!b_node->children().empty()) {\n if (!std::move(non_empty_folder_confirmation_cb).Run(b_node)) {\n \/\/ The folder is not empty and the user didn't confirm.\n return;\n }\n \/\/ The function above runs a nested loop so it's necessary to guard\n \/\/ against |node| having been deleted meanwhile (e.g. via extensions).\n node = tree_model_->AsNode(tree_view_->GetActiveNode());\n if (!node || node->value != bookmark_node_id) {\n \/\/ The active node has been deleted or has changed. In theory\n \/\/ FindNodeWithID() could be used to look up by |bookmark_node_id|,\n \/\/ but it's hard to reason about the desired behavior in this case, so\n \/\/ let's err on the safe side and avoid a deletion.\n return;\n }\n }\n deletes_.push_back(bookmark_node_id);\n }\n tree_model_->Remove(node->parent(), node);\n}\n\nvoid BookmarkEditorView::EditorTreeModel::SetTitle(\n ui::TreeModelNode* node,\n const std::u16string& title) {\n if (!title.empty())\n ui::TreeNodeModel::SetTitle(node, title);\n}\n\nBEGIN_METADATA(BookmarkEditorView, views::DialogDelegateView)\nADD_READONLY_PROPERTY_METADATA(GURL, InputURL)\nEND_METADATA\n","avg_line_length":36.3689320388,"max_line_length":80,"alphanum_fraction":0.70346147} {"size":1140,"ext":"cpp","lang":"C++","max_stars_count":36.0,"content":"\/* Adding Behavorial Movements*\/\n\n\n#include \nusing namespace std;\nclass Machine\n{\n\tclass State *current;\npublic:\n\tMachine();\n\tvoid setCurrent(State *s)\n\t{\n\t\tcurrent = s;\n\t}\n\tvoid Run();\n\tvoid Walk();\n};\n\nclass State\n{\npublic:\n\tvirtual void Run(Machine *m)\n\t{\n\t\tcout << \" Already Running\\n\";\n\t}\n\tvirtual void Walk(Machine *m)\n\t{\n\t\tcout << \" Already Walking\\n\";\n\t}\n};\n\nvoid Machine::Run()\n{\n\tcurrent->Run(this);\n}\n\nvoid Machine::Walk()\n{\n\tcurrent->Walk(this);\n}\n\nclass RUN : public State\n{\npublic:\n\tRUN()\n\t{\n\t\tcout << \" RUN-ctor \";\n\t};\n\t~RUN()\n\t{\n\t\tcout << \" dtor-RUN\\n\";\n\t};\n\tvoid Walk(Machine *m);\n};\n\nclass WALK : public State\n{\npublic:\n\tWALK()\n\t{\n\t\tcout << \" WALK-ctor \";\n\t};\n\t~WALK()\n\t{\n\t\tcout << \" dtor-WALK\\n\";\n\t};\n\tvoid Run(Machine *m)\n\t{\n\t\tcout << \" Changing behaviour from WALK to RUN\";\n\t\tm->setCurrent(new RUN());\n\t\tdelete this;\n\t}\n};\n\nvoid RUN::Walk(Machine *m)\n{\n\tcout << \" Changing behaviour RUN to WALK\";\n\tm->setCurrent(new WALK());\n\tdelete this;\n}\n\nMachine::Machine()\n{\n\tcurrent = new WALK();\n\tcout << '\\n';\n}\n\nint main()\n{\n\tMachine m;\n\tm.Run();\n\tm.Walk();\n\tm.Walk();\n\n\tint a;\n\tcin >> a;\n\n\treturn 0;\n}\n","avg_line_length":11.4,"max_line_length":49,"alphanum_fraction":0.5771929825} {"size":4190,"ext":"cc","lang":"C++","max_stars_count":null,"content":"\/*\n * libjingle\n * Copyright 2004 Google Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"base\/gunit.h\"\n#include \"media\/devices\/dummydevicemanager.h\"\n\nusing cricket::Device;\nusing cricket::DummyDeviceManager;\n\n\/\/ Test that we startup\/shutdown properly.\nTEST(DummyDeviceManagerTest, StartupShutdown) {\n DummyDeviceManager dm;\n EXPECT_TRUE(dm.Init());\n dm.Terminate();\n}\n\n\/\/ Test enumerating capabilities.\nTEST(DummyDeviceManagerTest, GetCapabilities) {\n DummyDeviceManager dm;\n int capabilities = dm.GetCapabilities();\n EXPECT_EQ((cricket::AUDIO_SEND | cricket::AUDIO_RECV |\n cricket::VIDEO_SEND | cricket::VIDEO_RECV), capabilities);\n}\n\n\/\/ Test enumerating devices.\nTEST(DummyDeviceManagerTest, GetDevices) {\n DummyDeviceManager dm;\n EXPECT_TRUE(dm.Init());\n std::vector audio_ins, audio_outs, video_ins;\n EXPECT_TRUE(dm.GetAudioInputDevices(&audio_ins));\n EXPECT_TRUE(dm.GetAudioOutputDevices(&audio_outs));\n EXPECT_TRUE(dm.GetVideoCaptureDevices(&video_ins));\n}\n\n\/\/ Test that we return correct ids for default and bogus devices.\nTEST(DummyDeviceManagerTest, GetAudioDeviceIds) {\n DummyDeviceManager dm;\n Device device;\n EXPECT_TRUE(dm.Init());\n EXPECT_TRUE(dm.GetAudioInputDevice(\n cricket::DeviceManagerInterface::kDefaultDeviceName, &device));\n EXPECT_EQ(\"-1\", device.id);\n EXPECT_TRUE(dm.GetAudioOutputDevice(\n cricket::DeviceManagerInterface::kDefaultDeviceName, &device));\n EXPECT_EQ(\"-1\", device.id);\n EXPECT_FALSE(dm.GetAudioInputDevice(\"_NOT A REAL DEVICE_\", &device));\n EXPECT_FALSE(dm.GetAudioOutputDevice(\"_NOT A REAL DEVICE_\", &device));\n}\n\n\/\/ Test that we get the video capture device by name properly.\nTEST(DummyDeviceManagerTest, GetVideoDeviceIds) {\n DummyDeviceManager dm;\n Device device;\n EXPECT_TRUE(dm.Init());\n EXPECT_FALSE(dm.GetVideoCaptureDevice(\"_NOT A REAL DEVICE_\", &device));\n EXPECT_TRUE(dm.GetVideoCaptureDevice(\n cricket::DeviceManagerInterface::kDefaultDeviceName, &device));\n}\n\nTEST(DummyDeviceManagerTest, VerifyDevicesListsAreCleared) {\n const std::string imaginary(\"_NOT A REAL DEVICE_\");\n DummyDeviceManager dm;\n std::vector audio_ins, audio_outs, video_ins;\n audio_ins.push_back(Device(imaginary, imaginary));\n audio_outs.push_back(Device(imaginary, imaginary));\n video_ins.push_back(Device(imaginary, imaginary));\n EXPECT_TRUE(dm.Init());\n EXPECT_TRUE(dm.GetAudioInputDevices(&audio_ins));\n EXPECT_TRUE(dm.GetAudioOutputDevices(&audio_outs));\n EXPECT_TRUE(dm.GetVideoCaptureDevices(&video_ins));\n for (size_t i = 0; i < audio_ins.size(); ++i) {\n EXPECT_NE(imaginary, audio_ins[i].name);\n }\n for (size_t i = 0; i < audio_outs.size(); ++i) {\n EXPECT_NE(imaginary, audio_outs[i].name);\n }\n for (size_t i = 0; i < video_ins.size(); ++i) {\n EXPECT_NE(imaginary, video_ins[i].name);\n }\n}\n","avg_line_length":39.9047619048,"max_line_length":80,"alphanum_fraction":0.7553699284} {"size":1554,"ext":"cpp","lang":"C++","max_stars_count":2.0,"content":"#include \n#define fi first\n#define se second\n#define maxn 3001\n#define maxh 200003\n#define mod 1000000007\n#define pb push_back\nusing namespace std;\ntypedef long long LL;\ntypedef pair pi;\n\nint n,h,w;\nint dp[maxn];\nint fac[maxh];\nint invFac[maxh];\nvector forb;\n\nbool comp( pi a , pi b ) {\n\treturn a.fi + a.se < b.fi + b.se;\n}\n\nint sub(int a, int b) {\n\treturn (a - b + mod) % mod;\n}\n\nint mult(int a, int b) {\n\treturn (LL) a * b % mod;\n}\n\nint calcPow(int a, int b) {\n\tif(b == 0)\n\t\treturn 1;\n\tint res = calcPow(a, b\/2);\n\tres = mult(res, res);\n\tif(b & 1)\n\t\tres = mult(res, a);\n\treturn res;\n}\n\nint calcInverse(int a) {\n\treturn calcPow(a, mod-2);\n}\n\nint calcComb(int a, int b) {\n\tif(a < 0 || b < 0 || b > a)\n\t\treturn 0;\n\treturn mult( fac[a] , mult( invFac[b] , invFac[a-b] ) );\n}\n\nint calcNoOfPaths(int row, int col) {\n\treturn calcComb(row+col, row);\n}\n\nint main() {\n\tfac[0] = invFac[0] = 1;\n\tfor( int i = 1 ; i < maxh ; i++ ) {\n\t\tfac[i] = mult( fac[i-1] , i );\n\t\tinvFac[i] = calcInverse( fac[i] );\n\t}\n\tscanf(\"%d%d%d\",&h,&w,&n);\n\tfor( int i = 0 ; i < n ; i++ ) {\n\t\tint x,y;\n\t\tscanf(\"%d%d\",&x,&y);\n\t\tforb.pb(pi(x,y));\n\t}\n\tforb.pb(pi(h,w));\n\tsort( forb.begin() , forb.end() , comp );\n\tfor( int i = 0 ; i <= n ; i++ ) {\n\t\tdp[i] = calcNoOfPaths(forb[i].fi-1, forb[i].se-1);\n\t\tfor( int j = 0 ; j < i ; j++ ) {\n\t\t\tint diffRow = forb[i].fi - forb[j].fi;\n\t\t\tint diffCol = forb[i].se - forb[j].se;\n\t\t\tint noOfPaths = calcNoOfPaths(diffRow, diffCol);\n\t\t\tdp[i] = sub( dp[i] , mult(dp[j], noOfPaths) );\n\t\t}\n\t}\n\tprintf(\"%d\\n\",dp[n]);\n\treturn 0;\n}\n","avg_line_length":19.425,"max_line_length":57,"alphanum_fraction":0.5592020592} {"size":847,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n#include \n#include \n#include \nusing std::complex;\nbool almost_equal(complex x, complex gold, float tol) {\n return std::abs(gold) * (1-tol) <= std::abs(x) && std::abs(x) <= std::abs(gold) * (1 + tol);\n}\n#pragma omp declare reduction(+: complex: omp_out += omp_in)\nvoid test_target_simd() {\n const int N0 { 32768 };\n const complex expected_value { N0 };\n complex counter_N0{};\n #pragma omp target simd map(tofrom: counter_N0) reduction(+: counter_N0)\n for (int i0 = 0 ; i0 < N0 ; i0++ )\n {\n counter_N0 = counter_N0 + complex { 1. };\n }\n if (!almost_equal(counter_N0, expected_value, 0.1)) {\n std::cerr << \"Expected: \" << expected_value << \" Got: \" << counter_N0 << std::endl;\n std::exit(112);\n }\n}\nint main()\n{\n test_target_simd();\n}\n","avg_line_length":30.25,"max_line_length":94,"alphanum_fraction":0.6422668241} {"size":3056,"ext":"hpp","lang":"C++","max_stars_count":null,"content":"\/*\n * @author Michael Rapp (mrapp@ke.tu-darmstadt.de)\n *\/\n#pragma once\n\n#include \"common\/data\/types.hpp\"\n#include \n\n\n\/**\n * An iterator that provides random access to the indices in a continuous range.\n *\/\nclass IndexIterator final {\n\n private:\n\n uint32 index_;\n\n public:\n\n IndexIterator();\n\n \/**\n * @param index The index to start with\n *\/\n IndexIterator(uint32 index);\n\n \/**\n * The type that is used to represent the difference between two iterators.\n *\/\n typedef int difference_type;\n\n \/**\n * The type of the elements, the iterator provides access to.\n *\/\n typedef uint32 value_type;\n\n \/**\n * The type of a pointer to an element, the iterator provides access to.\n *\/\n typedef uint32* pointer;\n\n \/**\n * The type of a reference to an element, the iterator provides access to.\n *\/\n typedef uint32 reference;\n\n \/**\n * The tag that specifies the capabilities of the iterator.\n *\/\n typedef std::random_access_iterator_tag iterator_category;\n\n \/**\n * Returns the element at a specific index.\n * @param index The index of the element to be returned\n * @return The element at the given index\n *\/\n reference operator[](uint32 index) const;\n\n \/**\n * Returns the element, the iterator currently refers to.\n *\n * @return The element, the iterator currently refers to\n *\/\n reference operator*() const;\n\n \/**\n * Returns an iterator to the next element.\n *\n * @return A reference to an iterator that refers to the next element\n *\/\n IndexIterator& operator++();\n\n \/**\n * Returns an iterator to the next element.\n *\n * @return A reference to an iterator that refers to the next element\n *\/\n IndexIterator& operator++(int n);\n\n \/**\n * Returns an iterator to the previous element.\n *\n * @return A reference to an iterator that refers to the previous element\n *\/\n IndexIterator& operator--();\n\n \/**\n * Returns an iterator to the previous element.\n *\n * @return A reference to an iterator that refers to the previous element\n *\/\n IndexIterator& operator--(int n);\n\n \/**\n * Returns whether this iterator and another one refer to the same element.\n *\n * @param rhs A reference to another iterator\n * @return True, if the iterators refer to the same element, false otherwise\n *\/\n bool operator!=(const IndexIterator& rhs) const;\n\n \/**\n * Returns the difference between this iterator and another one.\n *\n * @param rhs A reference to another iterator\n * @return The difference between the iterators\n *\/\n difference_type operator-(const IndexIterator& rhs) const;\n\n};\n","avg_line_length":27.2857142857,"max_line_length":89,"alphanum_fraction":0.5713350785} {"size":38612,"ext":"cc","lang":"C++","max_stars_count":null,"content":"\/\/\n\/\/ Copyright 2015 gRPC authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include \n\n#include \"src\/core\/ext\/filters\/client_channel\/subchannel.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"absl\/status\/statusor.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/ext\/filters\/client_channel\/health\/health_check_client.h\"\n#include \"src\/core\/ext\/filters\/client_channel\/proxy_mapper_registry.h\"\n#include \"src\/core\/ext\/filters\/client_channel\/subchannel_pool_interface.h\"\n#include \"src\/core\/ext\/filters\/client_channel\/subchannel_stream_client.h\"\n#include \"src\/core\/lib\/address_utils\/sockaddr_utils.h\"\n#include \"src\/core\/lib\/backoff\/backoff.h\"\n#include \"src\/core\/lib\/channel\/channel_args.h\"\n#include \"src\/core\/lib\/channel\/channel_stack.h\"\n#include \"src\/core\/lib\/channel\/channel_stack_builder.h\"\n#include \"src\/core\/lib\/channel\/channel_stack_builder_impl.h\"\n#include \"src\/core\/lib\/channel\/channel_trace.h\"\n#include \"src\/core\/lib\/channel\/channelz.h\"\n#include \"src\/core\/lib\/config\/core_configuration.h\"\n#include \"src\/core\/lib\/debug\/stats.h\"\n#include \"src\/core\/lib\/debug\/trace.h\"\n#include \"src\/core\/lib\/gpr\/alloc.h\"\n#include \"src\/core\/lib\/gprpp\/debug_location.h\"\n#include \"src\/core\/lib\/gprpp\/ref_counted_ptr.h\"\n#include \"src\/core\/lib\/gprpp\/sync.h\"\n#include \"src\/core\/lib\/iomgr\/exec_ctx.h\"\n#include \"src\/core\/lib\/iomgr\/pollset_set.h\"\n#include \"src\/core\/lib\/profiling\/timers.h\"\n#include \"src\/core\/lib\/surface\/channel_init.h\"\n#include \"src\/core\/lib\/surface\/channel_stack_type.h\"\n#include \"src\/core\/lib\/transport\/connectivity_state.h\"\n#include \"src\/core\/lib\/transport\/error_utils.h\"\n\n\/\/ Strong and weak refs.\n#define INTERNAL_REF_BITS 16\n#define STRONG_REF_MASK (~(gpr_atm)((1 << INTERNAL_REF_BITS) - 1))\n\n\/\/ Backoff parameters.\n#define GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS 1\n#define GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER 1.6\n#define GRPC_SUBCHANNEL_RECONNECT_MIN_TIMEOUT_SECONDS 20\n#define GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS 120\n#define GRPC_SUBCHANNEL_RECONNECT_JITTER 0.2\n\n\/\/ Conversion between subchannel call and call stack.\n#define SUBCHANNEL_CALL_TO_CALL_STACK(call) \\\n (grpc_call_stack*)((char*)(call) + \\\n GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)))\n#define CALL_STACK_TO_SUBCHANNEL_CALL(callstack) \\\n (SubchannelCall*)(((char*)(call_stack)) - \\\n GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)))\n\nnamespace grpc_core {\n\nTraceFlag grpc_trace_subchannel(false, \"subchannel\");\nDebugOnlyTraceFlag grpc_trace_subchannel_refcount(false, \"subchannel_refcount\");\n\n\/\/\n\/\/ ConnectedSubchannel\n\/\/\n\nConnectedSubchannel::ConnectedSubchannel(\n grpc_channel_stack* channel_stack, const grpc_channel_args* args,\n RefCountedPtr channelz_subchannel)\n : RefCounted(\n GRPC_TRACE_FLAG_ENABLED(grpc_trace_subchannel_refcount)\n ? \"ConnectedSubchannel\"\n : nullptr),\n channel_stack_(channel_stack),\n args_(grpc_channel_args_copy(args)),\n channelz_subchannel_(std::move(channelz_subchannel)) {}\n\nConnectedSubchannel::~ConnectedSubchannel() {\n grpc_channel_args_destroy(args_);\n GRPC_CHANNEL_STACK_UNREF(channel_stack_, \"connected_subchannel_dtor\");\n}\n\nvoid ConnectedSubchannel::StartWatch(\n grpc_pollset_set* interested_parties,\n OrphanablePtr watcher) {\n grpc_transport_op* op = grpc_make_transport_op(nullptr);\n op->start_connectivity_watch = std::move(watcher);\n op->start_connectivity_watch_state = GRPC_CHANNEL_READY;\n op->bind_pollset_set = interested_parties;\n grpc_channel_element* elem = grpc_channel_stack_element(channel_stack_, 0);\n elem->filter->start_transport_op(elem, op);\n}\n\nvoid ConnectedSubchannel::Ping(grpc_closure* on_initiate,\n grpc_closure* on_ack) {\n grpc_transport_op* op = grpc_make_transport_op(nullptr);\n grpc_channel_element* elem;\n op->send_ping.on_initiate = on_initiate;\n op->send_ping.on_ack = on_ack;\n elem = grpc_channel_stack_element(channel_stack_, 0);\n elem->filter->start_transport_op(elem, op);\n}\n\nsize_t ConnectedSubchannel::GetInitialCallSizeEstimate() const {\n return GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)) +\n channel_stack_->call_stack_size;\n}\n\n\/\/\n\/\/ SubchannelCall\n\/\/\n\nRefCountedPtr SubchannelCall::Create(Args args,\n grpc_error_handle* error) {\n const size_t allocation_size =\n args.connected_subchannel->GetInitialCallSizeEstimate();\n Arena* arena = args.arena;\n return RefCountedPtr(new (\n arena->Alloc(allocation_size)) SubchannelCall(std::move(args), error));\n}\n\nSubchannelCall::SubchannelCall(Args args, grpc_error_handle* error)\n : connected_subchannel_(std::move(args.connected_subchannel)),\n deadline_(args.deadline) {\n grpc_call_stack* callstk = SUBCHANNEL_CALL_TO_CALL_STACK(this);\n const grpc_call_element_args call_args = {\n callstk, \/* call_stack *\/\n nullptr, \/* server_transport_data *\/\n args.context, \/* context *\/\n args.path.c_slice(), \/* path *\/\n args.start_time, \/* start_time *\/\n args.deadline, \/* deadline *\/\n args.arena, \/* arena *\/\n args.call_combiner \/* call_combiner *\/\n };\n *error = grpc_call_stack_init(connected_subchannel_->channel_stack(), 1,\n SubchannelCall::Destroy, this, &call_args);\n if (GPR_UNLIKELY(*error != GRPC_ERROR_NONE)) {\n gpr_log(GPR_ERROR, \"error: %s\", grpc_error_std_string(*error).c_str());\n return;\n }\n grpc_call_stack_set_pollset_or_pollset_set(callstk, args.pollent);\n auto* channelz_node = connected_subchannel_->channelz_subchannel();\n if (channelz_node != nullptr) {\n channelz_node->RecordCallStarted();\n }\n}\n\nvoid SubchannelCall::StartTransportStreamOpBatch(\n grpc_transport_stream_op_batch* batch) {\n GPR_TIMER_SCOPE(\"subchannel_call_process_op\", 0);\n MaybeInterceptRecvTrailingMetadata(batch);\n grpc_call_stack* call_stack = SUBCHANNEL_CALL_TO_CALL_STACK(this);\n grpc_call_element* top_elem = grpc_call_stack_element(call_stack, 0);\n GRPC_CALL_LOG_OP(GPR_INFO, top_elem, batch);\n top_elem->filter->start_transport_stream_op_batch(top_elem, batch);\n}\n\ngrpc_call_stack* SubchannelCall::GetCallStack() {\n return SUBCHANNEL_CALL_TO_CALL_STACK(this);\n}\n\nvoid SubchannelCall::SetAfterCallStackDestroy(grpc_closure* closure) {\n GPR_ASSERT(after_call_stack_destroy_ == nullptr);\n GPR_ASSERT(closure != nullptr);\n after_call_stack_destroy_ = closure;\n}\n\nRefCountedPtr SubchannelCall::Ref() {\n IncrementRefCount();\n return RefCountedPtr(this);\n}\n\nRefCountedPtr SubchannelCall::Ref(const DebugLocation& location,\n const char* reason) {\n IncrementRefCount(location, reason);\n return RefCountedPtr(this);\n}\n\nvoid SubchannelCall::Unref() {\n GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), \"\");\n}\n\nvoid SubchannelCall::Unref(const DebugLocation& \/*location*\/,\n const char* reason) {\n GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason);\n}\n\nvoid SubchannelCall::Destroy(void* arg, grpc_error_handle \/*error*\/) {\n GPR_TIMER_SCOPE(\"subchannel_call_destroy\", 0);\n SubchannelCall* self = static_cast(arg);\n \/\/ Keep some members before destroying the subchannel call.\n grpc_closure* after_call_stack_destroy = self->after_call_stack_destroy_;\n RefCountedPtr connected_subchannel =\n std::move(self->connected_subchannel_);\n \/\/ Destroy the subchannel call.\n self->~SubchannelCall();\n \/\/ Destroy the call stack. This should be after destroying the subchannel\n \/\/ call, because call->after_call_stack_destroy(), if not null, will free the\n \/\/ call arena.\n grpc_call_stack_destroy(SUBCHANNEL_CALL_TO_CALL_STACK(self), nullptr,\n after_call_stack_destroy);\n \/\/ Automatically reset connected_subchannel. This should be after destroying\n \/\/ the call stack, because destroying call stack needs access to the channel\n \/\/ stack.\n}\n\nvoid SubchannelCall::MaybeInterceptRecvTrailingMetadata(\n grpc_transport_stream_op_batch* batch) {\n \/\/ only intercept payloads with recv trailing.\n if (!batch->recv_trailing_metadata) {\n return;\n }\n \/\/ only add interceptor is channelz is enabled.\n if (connected_subchannel_->channelz_subchannel() == nullptr) {\n return;\n }\n GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, RecvTrailingMetadataReady,\n this, grpc_schedule_on_exec_ctx);\n \/\/ save some state needed for the interception callback.\n GPR_ASSERT(recv_trailing_metadata_ == nullptr);\n recv_trailing_metadata_ =\n batch->payload->recv_trailing_metadata.recv_trailing_metadata;\n original_recv_trailing_metadata_ =\n batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready;\n batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready =\n &recv_trailing_metadata_ready_;\n}\n\nnamespace {\n\n\/\/ Sets *status based on the rest of the parameters.\nvoid GetCallStatus(grpc_status_code* status, Timestamp deadline,\n grpc_metadata_batch* md_batch, grpc_error_handle error) {\n if (error != GRPC_ERROR_NONE) {\n grpc_error_get_status(error, deadline, status, nullptr, nullptr, nullptr);\n } else {\n *status = md_batch->get(GrpcStatusMetadata()).value_or(GRPC_STATUS_UNKNOWN);\n }\n GRPC_ERROR_UNREF(error);\n}\n\n} \/\/ namespace\n\nvoid SubchannelCall::RecvTrailingMetadataReady(void* arg,\n grpc_error_handle error) {\n SubchannelCall* call = static_cast(arg);\n GPR_ASSERT(call->recv_trailing_metadata_ != nullptr);\n grpc_status_code status = GRPC_STATUS_OK;\n GetCallStatus(&status, call->deadline_, call->recv_trailing_metadata_,\n GRPC_ERROR_REF(error));\n channelz::SubchannelNode* channelz_subchannel =\n call->connected_subchannel_->channelz_subchannel();\n GPR_ASSERT(channelz_subchannel != nullptr);\n if (status == GRPC_STATUS_OK) {\n channelz_subchannel->RecordCallSucceeded();\n } else {\n channelz_subchannel->RecordCallFailed();\n }\n Closure::Run(DEBUG_LOCATION, call->original_recv_trailing_metadata_,\n GRPC_ERROR_REF(error));\n}\n\nvoid SubchannelCall::IncrementRefCount() {\n GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), \"\");\n}\n\nvoid SubchannelCall::IncrementRefCount(const DebugLocation& \/*location*\/,\n const char* reason) {\n GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason);\n}\n\n\/\/\n\/\/ Subchannel::ConnectedSubchannelStateWatcher\n\/\/\n\nclass Subchannel::ConnectedSubchannelStateWatcher\n : public AsyncConnectivityStateWatcherInterface {\n public:\n \/\/ Must be instantiated while holding c->mu.\n explicit ConnectedSubchannelStateWatcher(WeakRefCountedPtr c)\n : subchannel_(std::move(c)) {}\n\n ~ConnectedSubchannelStateWatcher() override {\n subchannel_.reset(DEBUG_LOCATION, \"state_watcher\");\n }\n\n private:\n void OnConnectivityStateChange(grpc_connectivity_state new_state,\n const absl::Status& status) override {\n Subchannel* c = subchannel_.get();\n MutexLock lock(&c->mu_);\n \/\/ If we're either shutting down or have already seen this connection\n \/\/ failure (i.e., c->connected_subchannel_ is null), do nothing.\n \/\/\n \/\/ The transport reports TRANSIENT_FAILURE upon GOAWAY but SHUTDOWN\n \/\/ upon connection close. So if the server gracefully shuts down,\n \/\/ we will see TRANSIENT_FAILURE followed by SHUTDOWN, but if not, we\n \/\/ will see only SHUTDOWN. Either way, we react to the first one we\n \/\/ see, ignoring anything that happens after that.\n if (c->connected_subchannel_ == nullptr) return;\n if (new_state == GRPC_CHANNEL_TRANSIENT_FAILURE ||\n new_state == GRPC_CHANNEL_SHUTDOWN) {\n if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_subchannel)) {\n gpr_log(GPR_INFO,\n \"subchannel %p %s: Connected subchannel %p reports %s: %s\", c,\n c->key_.ToString().c_str(), c->connected_subchannel_.get(),\n ConnectivityStateName(new_state), status.ToString().c_str());\n }\n c->connected_subchannel_.reset();\n if (c->channelz_node() != nullptr) {\n c->channelz_node()->SetChildSocket(nullptr);\n }\n \/\/ Even though we're reporting IDLE instead of TRANSIENT_FAILURE here,\n \/\/ pass along the status from the transport, since it may have\n \/\/ keepalive info attached to it that the channel needs.\n \/\/ TODO(roth): Consider whether there's a cleaner way to do this.\n c->SetConnectivityStateLocked(GRPC_CHANNEL_IDLE, status);\n c->backoff_.Reset();\n }\n }\n\n WeakRefCountedPtr subchannel_;\n};\n\n\/\/ Asynchronously notifies the \\a watcher of a change in the connectvity state\n\/\/ of \\a subchannel to the current \\a state. Deletes itself when done.\nclass Subchannel::AsyncWatcherNotifierLocked {\n public:\n AsyncWatcherNotifierLocked(\n RefCountedPtr watcher,\n grpc_connectivity_state state, const absl::Status& status)\n : watcher_(std::move(watcher)) {\n watcher_->PushConnectivityStateChange({state, status});\n ExecCtx::Run(DEBUG_LOCATION,\n GRPC_CLOSURE_INIT(\n &closure_,\n [](void* arg, grpc_error_handle \/*error*\/) {\n auto* self =\n static_cast(arg);\n self->watcher_->OnConnectivityStateChange();\n delete self;\n },\n this, nullptr),\n GRPC_ERROR_NONE);\n }\n\n private:\n RefCountedPtr watcher_;\n grpc_closure closure_;\n};\n\n\/\/\n\/\/ Subchannel::ConnectivityStateWatcherList\n\/\/\n\nvoid Subchannel::ConnectivityStateWatcherList::AddWatcherLocked(\n RefCountedPtr watcher) {\n watchers_.insert(std::make_pair(watcher.get(), std::move(watcher)));\n}\n\nvoid Subchannel::ConnectivityStateWatcherList::RemoveWatcherLocked(\n ConnectivityStateWatcherInterface* watcher) {\n watchers_.erase(watcher);\n}\n\nvoid Subchannel::ConnectivityStateWatcherList::NotifyLocked(\n grpc_connectivity_state state, const absl::Status& status) {\n for (const auto& p : watchers_) {\n new AsyncWatcherNotifierLocked(p.second, state, status);\n }\n}\n\n\/\/\n\/\/ Subchannel::HealthWatcherMap::HealthWatcher\n\/\/\n\n\/\/ State needed for tracking the connectivity state with a particular\n\/\/ health check service name.\nclass Subchannel::HealthWatcherMap::HealthWatcher\n : public AsyncConnectivityStateWatcherInterface {\n public:\n HealthWatcher(WeakRefCountedPtr c,\n std::string health_check_service_name)\n : subchannel_(std::move(c)),\n health_check_service_name_(std::move(health_check_service_name)),\n state_(subchannel_->state_ == GRPC_CHANNEL_READY\n ? GRPC_CHANNEL_CONNECTING\n : subchannel_->state_) {\n \/\/ If the subchannel is already connected, start health checking.\n if (subchannel_->state_ == GRPC_CHANNEL_READY) StartHealthCheckingLocked();\n }\n\n ~HealthWatcher() override {\n subchannel_.reset(DEBUG_LOCATION, \"health_watcher\");\n }\n\n const std::string& health_check_service_name() const {\n return health_check_service_name_;\n }\n\n grpc_connectivity_state state() const { return state_; }\n\n void AddWatcherLocked(\n grpc_connectivity_state initial_state,\n RefCountedPtr watcher) {\n if (state_ != initial_state) {\n new AsyncWatcherNotifierLocked(watcher, state_, status_);\n }\n watcher_list_.AddWatcherLocked(std::move(watcher));\n }\n\n void RemoveWatcherLocked(\n Subchannel::ConnectivityStateWatcherInterface* watcher) {\n watcher_list_.RemoveWatcherLocked(watcher);\n }\n\n bool HasWatchers() const { return !watcher_list_.empty(); }\n\n void NotifyLocked(grpc_connectivity_state state, const absl::Status& status)\n ABSL_EXCLUSIVE_LOCKS_REQUIRED(subchannel_->mu_) {\n if (state == GRPC_CHANNEL_READY) {\n \/\/ If we had not already notified for CONNECTING state, do so now.\n \/\/ (We may have missed this earlier, because if the transition\n \/\/ from IDLE to CONNECTING to READY was too quick, the connected\n \/\/ subchannel may not have sent us a notification for CONNECTING.)\n if (state_ != GRPC_CHANNEL_CONNECTING) {\n state_ = GRPC_CHANNEL_CONNECTING;\n status_ = status;\n watcher_list_.NotifyLocked(state_, status);\n }\n \/\/ If we've become connected, start health checking.\n StartHealthCheckingLocked();\n } else {\n state_ = state;\n status_ = status;\n watcher_list_.NotifyLocked(state_, status);\n \/\/ We're not connected, so stop health checking.\n health_check_client_.reset();\n }\n }\n\n void Orphan() override {\n watcher_list_.Clear();\n health_check_client_.reset();\n Unref();\n }\n\n private:\n void OnConnectivityStateChange(grpc_connectivity_state new_state,\n const absl::Status& status) override {\n MutexLock lock(&subchannel_->mu_);\n if (new_state != GRPC_CHANNEL_SHUTDOWN && health_check_client_ != nullptr) {\n state_ = new_state;\n status_ = status;\n watcher_list_.NotifyLocked(new_state, status);\n }\n }\n\n void StartHealthCheckingLocked()\n ABSL_EXCLUSIVE_LOCKS_REQUIRED(subchannel_->mu_) {\n GPR_ASSERT(health_check_client_ == nullptr);\n health_check_client_ = MakeHealthCheckClient(\n health_check_service_name_, subchannel_->connected_subchannel_,\n subchannel_->pollset_set_, subchannel_->channelz_node_, Ref());\n }\n\n WeakRefCountedPtr subchannel_;\n std::string health_check_service_name_;\n OrphanablePtr health_check_client_;\n grpc_connectivity_state state_;\n absl::Status status_;\n ConnectivityStateWatcherList watcher_list_;\n};\n\n\/\/\n\/\/ Subchannel::HealthWatcherMap\n\/\/\n\nvoid Subchannel::HealthWatcherMap::AddWatcherLocked(\n WeakRefCountedPtr subchannel,\n grpc_connectivity_state initial_state,\n const std::string& health_check_service_name,\n RefCountedPtr watcher) {\n \/\/ If the health check service name is not already present in the map,\n \/\/ add it.\n auto it = map_.find(health_check_service_name);\n HealthWatcher* health_watcher;\n if (it == map_.end()) {\n auto w = MakeOrphanable(std::move(subchannel),\n health_check_service_name);\n health_watcher = w.get();\n map_.emplace(health_check_service_name, std::move(w));\n } else {\n health_watcher = it->second.get();\n }\n \/\/ Add the watcher to the entry.\n health_watcher->AddWatcherLocked(initial_state, std::move(watcher));\n}\n\nvoid Subchannel::HealthWatcherMap::RemoveWatcherLocked(\n const std::string& health_check_service_name,\n ConnectivityStateWatcherInterface* watcher) {\n auto it = map_.find(health_check_service_name);\n GPR_ASSERT(it != map_.end());\n it->second->RemoveWatcherLocked(watcher);\n \/\/ If we just removed the last watcher for this service name, remove\n \/\/ the map entry.\n if (!it->second->HasWatchers()) map_.erase(it);\n}\n\nvoid Subchannel::HealthWatcherMap::NotifyLocked(grpc_connectivity_state state,\n const absl::Status& status) {\n for (const auto& p : map_) {\n p.second->NotifyLocked(state, status);\n }\n}\n\ngrpc_connectivity_state\nSubchannel::HealthWatcherMap::CheckConnectivityStateLocked(\n Subchannel* subchannel, const std::string& health_check_service_name) {\n auto it = map_.find(health_check_service_name);\n if (it == map_.end()) {\n \/\/ If the health check service name is not found in the map, we're\n \/\/ not currently doing a health check for that service name. If the\n \/\/ subchannel's state without health checking is READY, report\n \/\/ CONNECTING, since that's what we'd be in as soon as we do start a\n \/\/ watch. Otherwise, report the channel's state without health checking.\n return subchannel->state_ == GRPC_CHANNEL_READY ? GRPC_CHANNEL_CONNECTING\n : subchannel->state_;\n }\n HealthWatcher* health_watcher = it->second.get();\n return health_watcher->state();\n}\n\nvoid Subchannel::HealthWatcherMap::ShutdownLocked() { map_.clear(); }\n\n\/\/\n\/\/ Subchannel::ConnectivityStateWatcherInterface\n\/\/\n\nvoid Subchannel::ConnectivityStateWatcherInterface::PushConnectivityStateChange(\n ConnectivityStateChange state_change) {\n MutexLock lock(&mu_);\n connectivity_state_queue_.push_back(std::move(state_change));\n}\n\nSubchannel::ConnectivityStateWatcherInterface::ConnectivityStateChange\nSubchannel::ConnectivityStateWatcherInterface::PopConnectivityStateChange() {\n MutexLock lock(&mu_);\n GPR_ASSERT(!connectivity_state_queue_.empty());\n ConnectivityStateChange state_change = connectivity_state_queue_.front();\n connectivity_state_queue_.pop_front();\n return state_change;\n}\n\n\/\/\n\/\/ Subchannel\n\/\/\n\nnamespace {\n\nBackOff::Options ParseArgsForBackoffValues(const grpc_channel_args* args,\n Duration* min_connect_timeout) {\n Duration initial_backoff =\n Duration::Seconds(GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS);\n *min_connect_timeout =\n Duration::Seconds(GRPC_SUBCHANNEL_RECONNECT_MIN_TIMEOUT_SECONDS);\n Duration max_backoff =\n Duration::Seconds(GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS);\n bool fixed_reconnect_backoff = false;\n if (args != nullptr) {\n for (size_t i = 0; i < args->num_args; i++) {\n if (0 == strcmp(args->args[i].key,\n \"grpc.testing.fixed_reconnect_backoff_ms\")) {\n fixed_reconnect_backoff = true;\n initial_backoff = *min_connect_timeout = max_backoff =\n Duration::Milliseconds(grpc_channel_arg_get_integer(\n &args->args[i],\n {static_cast(initial_backoff.millis()), 100, INT_MAX}));\n } else if (0 ==\n strcmp(args->args[i].key, GRPC_ARG_MIN_RECONNECT_BACKOFF_MS)) {\n fixed_reconnect_backoff = false;\n *min_connect_timeout =\n Duration::Milliseconds(grpc_channel_arg_get_integer(\n &args->args[i],\n {static_cast(min_connect_timeout->millis()), 100,\n INT_MAX}));\n } else if (0 ==\n strcmp(args->args[i].key, GRPC_ARG_MAX_RECONNECT_BACKOFF_MS)) {\n fixed_reconnect_backoff = false;\n max_backoff = Duration::Milliseconds(grpc_channel_arg_get_integer(\n &args->args[i],\n {static_cast(max_backoff.millis()), 100, INT_MAX}));\n } else if (0 == strcmp(args->args[i].key,\n GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS)) {\n fixed_reconnect_backoff = false;\n initial_backoff = Duration::Milliseconds(grpc_channel_arg_get_integer(\n &args->args[i],\n {static_cast(initial_backoff.millis()), 100, INT_MAX}));\n }\n }\n }\n return BackOff::Options()\n .set_initial_backoff(initial_backoff)\n .set_multiplier(fixed_reconnect_backoff\n ? 1.0\n : GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER)\n .set_jitter(fixed_reconnect_backoff ? 0.0\n : GRPC_SUBCHANNEL_RECONNECT_JITTER)\n .set_max_backoff(max_backoff);\n}\n\n} \/\/ namespace\n\nSubchannel::Subchannel(SubchannelKey key,\n OrphanablePtr connector,\n const grpc_channel_args* args)\n : DualRefCounted(\n GRPC_TRACE_FLAG_ENABLED(grpc_trace_subchannel_refcount) ? \"Subchannel\"\n : nullptr),\n key_(std::move(key)),\n pollset_set_(grpc_pollset_set_create()),\n connector_(std::move(connector)),\n backoff_(ParseArgsForBackoffValues(args, &min_connect_timeout_)) {\n GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED();\n GRPC_CLOSURE_INIT(&on_connecting_finished_, OnConnectingFinished, this,\n grpc_schedule_on_exec_ctx);\n GRPC_CLOSURE_INIT(&on_retry_timer_, OnRetryTimer, this, nullptr);\n \/\/ Check proxy mapper to determine address to connect to and channel\n \/\/ args to use.\n address_for_connect_ = key_.address();\n grpc_resolved_address* new_address = nullptr;\n grpc_channel_args* new_args = nullptr;\n if (ProxyMapperRegistry::MapAddress(address_for_connect_, args, &new_address,\n &new_args)) {\n GPR_ASSERT(new_address != nullptr);\n address_for_connect_ = *new_address;\n gpr_free(new_address);\n }\n if (new_args != nullptr) {\n args_ = new_args;\n } else {\n args_ = grpc_channel_args_copy(args);\n }\n \/\/ Initialize channelz.\n const bool channelz_enabled = grpc_channel_args_find_bool(\n args_, GRPC_ARG_ENABLE_CHANNELZ, GRPC_ENABLE_CHANNELZ_DEFAULT);\n if (channelz_enabled) {\n const size_t channel_tracer_max_memory =\n static_cast(grpc_channel_args_find_integer(\n args_, GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE,\n {GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT, 0,\n INT_MAX}));\n channelz_node_ = MakeRefCounted(\n grpc_sockaddr_to_uri(&key_.address())\n .value_or(\"\"),\n channel_tracer_max_memory);\n channelz_node_->AddTraceEvent(\n channelz::ChannelTrace::Severity::Info,\n grpc_slice_from_static_string(\"subchannel created\"));\n }\n}\n\nSubchannel::~Subchannel() {\n if (channelz_node_ != nullptr) {\n channelz_node_->AddTraceEvent(\n channelz::ChannelTrace::Severity::Info,\n grpc_slice_from_static_string(\"Subchannel destroyed\"));\n channelz_node_->UpdateConnectivityState(GRPC_CHANNEL_SHUTDOWN);\n }\n grpc_channel_args_destroy(args_);\n connector_.reset();\n grpc_pollset_set_destroy(pollset_set_);\n}\n\nRefCountedPtr Subchannel::Create(\n OrphanablePtr connector,\n const grpc_resolved_address& address, const grpc_channel_args* args) {\n SubchannelKey key(address, args);\n SubchannelPoolInterface* subchannel_pool =\n SubchannelPoolInterface::GetSubchannelPoolFromChannelArgs(args);\n GPR_ASSERT(subchannel_pool != nullptr);\n RefCountedPtr c = subchannel_pool->FindSubchannel(key);\n if (c != nullptr) {\n return c;\n }\n c = MakeRefCounted(std::move(key), std::move(connector), args);\n \/\/ Try to register the subchannel before setting the subchannel pool.\n \/\/ Otherwise, in case of a registration race, unreffing c in\n \/\/ RegisterSubchannel() will cause c to be tried to be unregistered, while\n \/\/ its key maps to a different subchannel.\n RefCountedPtr registered =\n subchannel_pool->RegisterSubchannel(c->key_, c);\n if (registered == c) c->subchannel_pool_ = subchannel_pool->Ref();\n return registered;\n}\n\nvoid Subchannel::ThrottleKeepaliveTime(int new_keepalive_time) {\n MutexLock lock(&mu_);\n \/\/ Only update the value if the new keepalive time is larger.\n if (new_keepalive_time > keepalive_time_) {\n keepalive_time_ = new_keepalive_time;\n if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_subchannel)) {\n gpr_log(GPR_INFO, \"subchannel %p %s: throttling keepalive time to %d\",\n this, key_.ToString().c_str(), new_keepalive_time);\n }\n const grpc_arg arg_to_add = grpc_channel_arg_integer_create(\n const_cast(GRPC_ARG_KEEPALIVE_TIME_MS), new_keepalive_time);\n const char* arg_to_remove = GRPC_ARG_KEEPALIVE_TIME_MS;\n grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(\n args_, &arg_to_remove, 1, &arg_to_add, 1);\n grpc_channel_args_destroy(args_);\n args_ = new_args;\n }\n}\n\nchannelz::SubchannelNode* Subchannel::channelz_node() {\n return channelz_node_.get();\n}\n\ngrpc_connectivity_state Subchannel::CheckConnectivityState(\n const absl::optional& health_check_service_name) {\n MutexLock lock(&mu_);\n if (health_check_service_name.has_value()) {\n return health_watcher_map_.CheckConnectivityStateLocked(\n this, *health_check_service_name);\n }\n return state_;\n}\n\nvoid Subchannel::WatchConnectivityState(\n grpc_connectivity_state initial_state,\n const absl::optional& health_check_service_name,\n RefCountedPtr watcher) {\n MutexLock lock(&mu_);\n grpc_pollset_set* interested_parties = watcher->interested_parties();\n if (interested_parties != nullptr) {\n grpc_pollset_set_add_pollset_set(pollset_set_, interested_parties);\n }\n if (!health_check_service_name.has_value()) {\n if (state_ != initial_state) {\n new AsyncWatcherNotifierLocked(watcher, state_, status_);\n }\n watcher_list_.AddWatcherLocked(std::move(watcher));\n } else {\n health_watcher_map_.AddWatcherLocked(\n WeakRef(DEBUG_LOCATION, \"health_watcher\"), initial_state,\n *health_check_service_name, std::move(watcher));\n }\n}\n\nvoid Subchannel::CancelConnectivityStateWatch(\n const absl::optional& health_check_service_name,\n ConnectivityStateWatcherInterface* watcher) {\n MutexLock lock(&mu_);\n grpc_pollset_set* interested_parties = watcher->interested_parties();\n if (interested_parties != nullptr) {\n grpc_pollset_set_del_pollset_set(pollset_set_, interested_parties);\n }\n if (!health_check_service_name.has_value()) {\n watcher_list_.RemoveWatcherLocked(watcher);\n } else {\n health_watcher_map_.RemoveWatcherLocked(*health_check_service_name,\n watcher);\n }\n}\n\nvoid Subchannel::RequestConnection() {\n MutexLock lock(&mu_);\n if (state_ == GRPC_CHANNEL_IDLE) {\n StartConnectingLocked();\n } else if (state_ == GRPC_CHANNEL_TRANSIENT_FAILURE) {\n connection_requested_ = true;\n }\n}\n\nvoid Subchannel::ResetBackoff() {\n MutexLock lock(&mu_);\n backoff_.Reset();\n if (state_ == GRPC_CHANNEL_TRANSIENT_FAILURE) {\n grpc_timer_cancel(&retry_timer_);\n } else if (state_ == GRPC_CHANNEL_CONNECTING) {\n next_attempt_time_ = ExecCtx::Get()->Now();\n }\n}\n\nvoid Subchannel::Orphan() {\n \/\/ The subchannel_pool is only used once here in this subchannel, so the\n \/\/ access can be outside of the lock.\n if (subchannel_pool_ != nullptr) {\n subchannel_pool_->UnregisterSubchannel(key_, this);\n subchannel_pool_.reset();\n }\n MutexLock lock(&mu_);\n GPR_ASSERT(!shutdown_);\n shutdown_ = true;\n connector_.reset();\n connected_subchannel_.reset();\n health_watcher_map_.ShutdownLocked();\n}\n\nvoid Subchannel::AddDataProducer(DataProducerInterface* data_producer) {\n MutexLock lock(&mu_);\n auto& entry = data_producer_map_[data_producer->type()];\n GPR_ASSERT(entry == nullptr);\n entry = data_producer;\n}\n\nvoid Subchannel::RemoveDataProducer(DataProducerInterface* data_producer) {\n MutexLock lock(&mu_);\n auto it = data_producer_map_.find(data_producer->type());\n GPR_ASSERT(it != data_producer_map_.end());\n GPR_ASSERT(it->second == data_producer);\n data_producer_map_.erase(it);\n}\n\nSubchannel::DataProducerInterface* Subchannel::GetDataProducer(\n UniqueTypeName type) {\n MutexLock lock(&mu_);\n auto it = data_producer_map_.find(type);\n if (it == data_producer_map_.end()) return nullptr;\n return it->second;\n}\n\nnamespace {\n\n\/\/ Returns a string indicating the subchannel's connectivity state change to\n\/\/ \\a state.\nconst char* SubchannelConnectivityStateChangeString(\n grpc_connectivity_state state) {\n switch (state) {\n case GRPC_CHANNEL_IDLE:\n return \"Subchannel state change to IDLE\";\n case GRPC_CHANNEL_CONNECTING:\n return \"Subchannel state change to CONNECTING\";\n case GRPC_CHANNEL_READY:\n return \"Subchannel state change to READY\";\n case GRPC_CHANNEL_TRANSIENT_FAILURE:\n return \"Subchannel state change to TRANSIENT_FAILURE\";\n case GRPC_CHANNEL_SHUTDOWN:\n return \"Subchannel state change to SHUTDOWN\";\n }\n GPR_UNREACHABLE_CODE(return \"UNKNOWN\");\n}\n\n} \/\/ namespace\n\n\/\/ Note: Must be called with a state that is different from the current state.\nvoid Subchannel::SetConnectivityStateLocked(grpc_connectivity_state state,\n const absl::Status& status) {\n state_ = state;\n status_ = status;\n if (channelz_node_ != nullptr) {\n channelz_node_->UpdateConnectivityState(state);\n channelz_node_->AddTraceEvent(\n channelz::ChannelTrace::Severity::Info,\n grpc_slice_from_static_string(\n SubchannelConnectivityStateChangeString(state)));\n }\n \/\/ Notify non-health watchers.\n watcher_list_.NotifyLocked(state, status);\n \/\/ Notify health watchers.\n health_watcher_map_.NotifyLocked(state, status);\n}\n\nvoid Subchannel::OnRetryTimer(void* arg, grpc_error_handle \/*error*\/) {\n WeakRefCountedPtr c(static_cast(arg));\n {\n MutexLock lock(&c->mu_);\n c->OnRetryTimerLocked();\n }\n c.reset(DEBUG_LOCATION, \"RetryTimer\");\n}\n\nvoid Subchannel::OnRetryTimerLocked() {\n if (shutdown_) return;\n if (connection_requested_) {\n gpr_log(GPR_INFO,\n \"subchannel %p %s: connection attempt requested while backoff \"\n \"timer was pending, retrying now\",\n this, key_.ToString().c_str());\n connection_requested_ = false;\n StartConnectingLocked();\n } else {\n gpr_log(GPR_INFO, \"subchannel %p %s: backoff delay elapsed, reporting IDLE\",\n this, key_.ToString().c_str());\n SetConnectivityStateLocked(GRPC_CHANNEL_IDLE, absl::OkStatus());\n }\n}\n\nvoid Subchannel::StartConnectingLocked() {\n \/\/ Set next attempt time.\n const Timestamp min_deadline = min_connect_timeout_ + ExecCtx::Get()->Now();\n next_attempt_time_ = backoff_.NextAttemptTime();\n \/\/ Report CONNECTING.\n SetConnectivityStateLocked(GRPC_CHANNEL_CONNECTING, absl::OkStatus());\n \/\/ Start connection attempt.\n SubchannelConnector::Args args;\n args.address = &address_for_connect_;\n args.interested_parties = pollset_set_;\n args.deadline = std::max(next_attempt_time_, min_deadline);\n args.channel_args = args_;\n WeakRef(DEBUG_LOCATION, \"Connect\").release(); \/\/ Ref held by callback.\n connector_->Connect(args, &connecting_result_, &on_connecting_finished_);\n}\n\nvoid Subchannel::OnConnectingFinished(void* arg, grpc_error_handle error) {\n WeakRefCountedPtr c(static_cast(arg));\n const grpc_channel_args* delete_channel_args =\n c->connecting_result_.channel_args;\n {\n MutexLock lock(&c->mu_);\n c->OnConnectingFinishedLocked(GRPC_ERROR_REF(error));\n }\n grpc_channel_args_destroy(delete_channel_args);\n c.reset(DEBUG_LOCATION, \"Connect\");\n}\n\nvoid Subchannel::OnConnectingFinishedLocked(grpc_error_handle error) {\n if (shutdown_) {\n (void)GRPC_ERROR_UNREF(error);\n return;\n }\n \/\/ If we didn't get a transport or we fail to publish it, report\n \/\/ TRANSIENT_FAILURE and start the retry timer.\n \/\/ Note that if the connection attempt took longer than the backoff\n \/\/ time, then the timer will fire immediately, and we will quickly\n \/\/ transition back to IDLE.\n if (connecting_result_.transport == nullptr || !PublishTransportLocked()) {\n const Duration time_until_next_attempt =\n next_attempt_time_ - ExecCtx::Get()->Now();\n gpr_log(GPR_INFO,\n \"subchannel %p %s: connect failed (%s), backing off for %\" PRId64\n \" ms\",\n this, key_.ToString().c_str(), grpc_error_std_string(error).c_str(),\n time_until_next_attempt.millis());\n SetConnectivityStateLocked(GRPC_CHANNEL_TRANSIENT_FAILURE,\n grpc_error_to_absl_status(error));\n WeakRef(DEBUG_LOCATION, \"RetryTimer\").release(); \/\/ Ref held by callback.\n grpc_timer_init(&retry_timer_, next_attempt_time_, &on_retry_timer_);\n }\n (void)GRPC_ERROR_UNREF(error);\n}\n\nbool Subchannel::PublishTransportLocked() {\n \/\/ Construct channel stack.\n ChannelStackBuilderImpl builder(\"subchannel\", GRPC_CLIENT_SUBCHANNEL);\n builder.SetChannelArgs(ChannelArgs::FromC(connecting_result_.channel_args))\n .SetTransport(connecting_result_.transport);\n if (!CoreConfiguration::Get().channel_init().CreateStack(&builder)) {\n return false;\n }\n absl::StatusOr> stk = builder.Build();\n if (!stk.ok()) {\n auto error = absl_status_to_grpc_error(stk.status());\n grpc_transport_destroy(connecting_result_.transport);\n gpr_log(GPR_ERROR,\n \"subchannel %p %s: error initializing subchannel stack: %s\", this,\n key_.ToString().c_str(), grpc_error_std_string(error).c_str());\n GRPC_ERROR_UNREF(error);\n return false;\n }\n RefCountedPtr socket =\n std::move(connecting_result_.socket_node);\n connecting_result_.Reset();\n if (shutdown_) return false;\n \/\/ Publish.\n connected_subchannel_.reset(\n new ConnectedSubchannel(stk->release(), args_, channelz_node_));\n if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_subchannel)) {\n gpr_log(GPR_INFO, \"subchannel %p %s: new connected subchannel at %p\", this,\n key_.ToString().c_str(), connected_subchannel_.get());\n }\n if (channelz_node_ != nullptr) {\n channelz_node_->SetChildSocket(std::move(socket));\n }\n \/\/ Start watching connected subchannel.\n connected_subchannel_->StartWatch(\n pollset_set_, MakeOrphanable(\n WeakRef(DEBUG_LOCATION, \"state_watcher\")));\n \/\/ Report initial state.\n SetConnectivityStateLocked(GRPC_CHANNEL_READY, absl::Status());\n return true;\n}\n\n} \/\/ namespace grpc_core\n","avg_line_length":38.0788954635,"max_line_length":80,"alphanum_fraction":0.7176525433} {"size":1321,"ext":"hpp","lang":"C++","max_stars_count":1.0,"content":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The following FIT Protocol software provided may be used with FIT protocol\n\/\/ devices only and remains the copyrighted property of Dynastream Innovations Inc.\n\/\/ The software is being provided on an \"as-is\" basis and as an accommodation,\n\/\/ and therefore all warranties, representations, or guarantees of any kind\n\/\/ (whether express, implied or statutory) including, without limitation,\n\/\/ warranties of merchantability, non-infringement, or fitness for a particular\n\/\/ purpose, are specifically disclaimed.\n\/\/\n\/\/ Copyright 2017 Dynastream Innovations Inc.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ****WARNING**** This file is auto-generated! Do NOT edit this file.\n\/\/ Profile Version = 20.38Release\n\/\/ Tag = production\/akw\/20.38.00-0-geccbce3\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#if !defined(FIT_CAPABILITIES_MESG_LISTENER_HPP)\n#define FIT_CAPABILITIES_MESG_LISTENER_HPP\n\n#include \"fit_capabilities_mesg.hpp\"\n\nnamespace fit\n{\n\nclass CapabilitiesMesgListener\n{\npublic:\n virtual ~CapabilitiesMesgListener() {}\n virtual void OnMesg(CapabilitiesMesg& mesg) = 0;\n};\n\n} \/\/ namespace fit\n\n#endif \/\/ !defined(FIT_CAPABILITIES_MESG_LISTENER_HPP)\n","avg_line_length":36.6944444444,"max_line_length":83,"alphanum_fraction":0.6320968963} {"size":107273,"ext":"cc","lang":"C++","max_stars_count":null,"content":"#include \"commands.hh\"\n\n#include \"buffer.hh\"\n#include \"buffer_manager.hh\"\n#include \"buffer_utils.hh\"\n#include \"client.hh\"\n#include \"client_manager.hh\"\n#include \"command_manager.hh\"\n#include \"completion.hh\"\n#include \"context.hh\"\n#include \"event_manager.hh\"\n#include \"face_registry.hh\"\n#include \"file.hh\"\n#include \"hash_map.hh\"\n#include \"highlighter.hh\"\n#include \"highlighters.hh\"\n#include \"insert_completer.hh\"\n#include \"normal.hh\"\n#include \"option_manager.hh\"\n#include \"option_types.hh\"\n#include \"parameters_parser.hh\"\n#include \"ranges.hh\"\n#include \"ranked_match.hh\"\n#include \"regex.hh\"\n#include \"register_manager.hh\"\n#include \"remote.hh\"\n#include \"shell_manager.hh\"\n#include \"string.hh\"\n#include \"user_interface.hh\"\n#include \"window.hh\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#if defined(__GLIBC__) || defined(__CYGWIN__)\n#include \n#endif\n\nnamespace Kakoune\n{\n\nextern const char* version;\n\nnamespace\n{\n\nBuffer* open_fifo(StringView name, StringView filename, Buffer::Flags flags, bool scroll)\n{\n int fd = open(parse_filename(filename).c_str(), O_RDONLY | O_NONBLOCK);\n fcntl(fd, F_SETFD, FD_CLOEXEC);\n if (fd < 0)\n throw runtime_error(format(\"unable to open '{}'\", filename));\n\n return create_fifo_buffer(name.str(), fd, flags, scroll);\n}\n\ntemplate struct PerArgumentCommandCompleter;\n\ntemplate<> struct PerArgumentCommandCompleter<>\n{\n Completions operator()(const Context&, CompletionFlags, CommandParameters,\n size_t, ByteCount) const { return {}; }\n};\n\ntemplate\nstruct PerArgumentCommandCompleter : PerArgumentCommandCompleter\n{\n template,\n std::remove_reference_t>::value>>\n PerArgumentCommandCompleter(C&& completer, R&&... rest)\n : PerArgumentCommandCompleter(std::forward(rest)...),\n m_completer(std::forward(completer)) {}\n\n Completions operator()(const Context& context, CompletionFlags flags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token) const\n {\n if (token_to_complete == 0)\n {\n const String& arg = token_to_complete < params.size() ?\n params[token_to_complete] : String();\n return m_completer(context, flags, arg, pos_in_token);\n }\n return PerArgumentCommandCompleter::operator()(\n context, flags, params.subrange(1),\n token_to_complete-1, pos_in_token);\n }\n\n Completer m_completer;\n};\n\ntemplate\nPerArgumentCommandCompleter...>\nmake_completer(Completers&&... completers)\n{\n return {std::forward(completers)...};\n}\n\ntemplate\nauto add_flags(Completer completer, Completions::Flags completions_flags)\n{\n return [completer=std::move(completer), completions_flags]\n (const Context& context, CompletionFlags flags, const String& prefix, ByteCount cursor_pos) {\n Completions res = completer(context, flags, prefix, cursor_pos);\n res.flags |= completions_flags;\n return res;\n };\n}\n\ntemplate\nauto menu(Completer completer)\n{\n return add_flags(std::move(completer), Completions::Flags::Menu);\n}\n\ntemplate\nauto filename_completer = make_completer(\n [](const Context& context, CompletionFlags flags, const String& prefix, ByteCount cursor_pos)\n { return Completions{ 0_byte, cursor_pos,\n complete_filename(prefix,\n context.options()[\"ignored_files\"].get(),\n cursor_pos, FilenameFlags::Expand),\n menu ? Completions::Flags::Menu : Completions::Flags::None}; });\n\ntemplate\nstatic Completions complete_buffer_name(const Context& context, CompletionFlags flags,\n StringView prefix, ByteCount cursor_pos)\n{\n struct RankedMatchAndBuffer : RankedMatch\n {\n RankedMatchAndBuffer(RankedMatch m, const Buffer* b)\n : RankedMatch{std::move(m)}, buffer{b} {}\n\n using RankedMatch::operator==;\n using RankedMatch::operator<;\n\n const Buffer* buffer;\n };\n\n StringView query = prefix.substr(0, cursor_pos);\n Vector filename_matches;\n Vector matches;\n for (const auto& buffer : BufferManager::instance())\n {\n if (ignore_current and buffer.get() == &context.buffer())\n continue;\n\n StringView bufname = buffer->display_name();\n if (buffer->flags() & Buffer::Flags::File)\n {\n if (RankedMatch match{split_path(bufname).second, query})\n {\n filename_matches.emplace_back(match, buffer.get());\n continue;\n }\n }\n if (RankedMatch match{bufname, query})\n matches.emplace_back(match, buffer.get());\n }\n std::sort(filename_matches.begin(), filename_matches.end());\n std::sort(matches.begin(), matches.end());\n\n CandidateList res;\n for (auto& match : filename_matches)\n res.push_back(match.buffer->display_name());\n for (auto& match : matches)\n res.push_back(match.buffer->display_name());\n\n return { 0, cursor_pos, res };\n}\n\ntemplate\nauto make_single_word_completer(Func&& func)\n{\n return make_completer(\n [func = std::move(func)](const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos) -> Completions {\n auto candidate = { func(context) };\n return { 0_byte, cursor_pos, complete(prefix, cursor_pos, candidate) }; });\n}\n\nconst ParameterDesc no_params{ {}, ParameterDesc::Flags::None, 0, 0 };\nconst ParameterDesc single_param{ {}, ParameterDesc::Flags::None, 1, 1 };\nconst ParameterDesc single_optional_param{ {}, ParameterDesc::Flags::None, 0, 1 };\nconst ParameterDesc double_params{ {}, ParameterDesc::Flags::None, 2, 2 };\n\nstatic constexpr auto scopes = { \"global\", \"buffer\", \"window\" };\n\nstatic Completions complete_scope(const Context&, CompletionFlags,\n const String& prefix, ByteCount cursor_pos)\n{\n return { 0_byte, cursor_pos, complete(prefix, cursor_pos, scopes) };\n}\n\n\nstatic Completions complete_command_name(const Context& context, CompletionFlags,\n const String& prefix, ByteCount cursor_pos)\n{\n return CommandManager::instance().complete_command_name(\n context, prefix.substr(0, cursor_pos));\n}\n\nstruct ShellScriptCompleter\n{\n ShellScriptCompleter(String shell_script,\n Completions::Flags flags = Completions::Flags::None)\n : m_shell_script{std::move(shell_script)}, m_flags(flags) {}\n\n Completions operator()(const Context& context, CompletionFlags flags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token)\n {\n if (flags & CompletionFlags::Fast) \/\/ no shell on fast completion\n return Completions{};\n\n ShellContext shell_context{\n params,\n { { \"token_to_complete\", to_string(token_to_complete) },\n { \"pos_in_token\", to_string(pos_in_token) } }\n };\n String output = ShellManager::instance().eval(m_shell_script, context, {},\n ShellManager::Flags::WaitForStdout,\n shell_context).first;\n CandidateList candidates;\n for (auto&& candidate : output | split('\\n'))\n candidates.push_back(candidate.str());\n\n return {0_byte, pos_in_token, std::move(candidates), m_flags};\n }\nprivate:\n String m_shell_script;\n Completions::Flags m_flags;\n};\n\nstruct ShellCandidatesCompleter\n{\n ShellCandidatesCompleter(String shell_script,\n Completions::Flags flags = Completions::Flags::None)\n : m_shell_script{std::move(shell_script)}, m_flags(flags) {}\n\n Completions operator()(const Context& context, CompletionFlags flags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token)\n {\n if (flags & CompletionFlags::Start)\n m_token = -1;\n\n if (m_token != token_to_complete)\n {\n ShellContext shell_context{\n params,\n { { \"token_to_complete\", to_string(token_to_complete) } }\n };\n String output = ShellManager::instance().eval(m_shell_script, context, {},\n ShellManager::Flags::WaitForStdout,\n shell_context).first;\n m_candidates.clear();\n for (auto c : output | split('\\n'))\n m_candidates.emplace_back(c.str(), used_letters(c));\n m_token = token_to_complete;\n }\n\n StringView query = params[token_to_complete].substr(0, pos_in_token);\n UsedLetters query_letters = used_letters(query);\n Vector matches;\n for (const auto& candidate : m_candidates)\n {\n if (RankedMatch match{candidate.first, candidate.second, query, query_letters})\n matches.push_back(match);\n }\n\n constexpr size_t max_count = 100;\n CandidateList res;\n \/\/ Gather best max_count matches\n for_n_best(matches, max_count, [](auto& lhs, auto& rhs) { return rhs < lhs; },\n [&] (const RankedMatch& m) {\n if (not res.empty() and res.back() == m.candidate())\n return false;\n res.push_back(m.candidate().str());\n return true;\n });\n\n return Completions{0_byte, pos_in_token, std::move(res), m_flags};\n }\n\nprivate:\n String m_shell_script;\n Vector, MemoryDomain::Completion> m_candidates;\n int m_token = -1;\n Completions::Flags m_flags;\n};\n\ntemplate\nstruct PromptCompleterAdapter\n{\n PromptCompleterAdapter(Completer completer) : m_completer{completer} {}\n\n Completions operator()(const Context& context, CompletionFlags flags,\n StringView prefix, ByteCount cursor_pos)\n {\n return m_completer(context, flags, {String{String::NoCopy{}, prefix}}, 0, cursor_pos);\n }\n\nprivate:\n Completer m_completer;\n};\n\nScope* get_scope_ifp(StringView scope, const Context& context)\n{\n if (prefix_match(\"global\", scope))\n return &GlobalScope::instance();\n else if (prefix_match(\"buffer\", scope))\n return &context.buffer();\n else if (prefix_match(\"window\", scope))\n return &context.window();\n else if (prefix_match(scope, \"buffer=\"))\n return &BufferManager::instance().get_buffer(scope.substr(7_byte));\n return nullptr;\n}\n\nScope& get_scope(StringView scope, const Context& context)\n{\n if (auto s = get_scope_ifp(scope, context))\n return *s;\n throw runtime_error(format(\"no such scope: '{}'\", scope));\n}\n\nstruct CommandDesc\n{\n const char* name;\n const char* alias;\n const char* docstring;\n ParameterDesc params;\n CommandFlags flags;\n CommandHelper helper;\n CommandCompleter completer;\n void (*func)(const ParametersParser&, Context&, const ShellContext&);\n};\n\ntemplate\nvoid edit(const ParametersParser& parser, Context& context, const ShellContext&)\n{\n const bool scratch = (bool)parser.get_switch(\"scratch\");\n\n if (parser.positional_count() == 0 and not force_reload and not scratch)\n throw wrong_argument_count();\n\n const bool no_hooks = context.hooks_disabled();\n const auto flags = (no_hooks ? Buffer::Flags::NoHooks : Buffer::Flags::None) |\n (parser.get_switch(\"debug\") ? Buffer::Flags::Debug : Buffer::Flags::None);\n\n auto& buffer_manager = BufferManager::instance();\n const auto& name = parser.positional_count() > 0 ?\n parser[0] : (scratch ? generate_buffer_name(\"*scratch-{}*\") : context.buffer().name());\n\n Buffer* buffer = buffer_manager.get_buffer_ifp(name);\n if (scratch)\n {\n if (parser.get_switch(\"readonly\") or parser.get_switch(\"fifo\") or parser.get_switch(\"scroll\"))\n throw runtime_error(\"scratch is not compatible with readonly, fifo or scroll\");\n\n if (buffer == nullptr or force_reload)\n {\n if (buffer != nullptr and force_reload)\n buffer_manager.delete_buffer(*buffer);\n buffer = create_buffer_from_string(std::move(name), flags, {});\n }\n else if (buffer->flags() & Buffer::Flags::File)\n throw runtime_error(format(\"buffer '{}' exists but is not a scratch buffer\", name));\n }\n else if (force_reload and buffer and buffer->flags() & Buffer::Flags::File)\n {\n reload_file_buffer(*buffer);\n }\n else\n {\n if (auto fifo = parser.get_switch(\"fifo\"))\n buffer = open_fifo(name, *fifo, flags, (bool)parser.get_switch(\"scroll\"));\n else if (not buffer)\n {\n buffer = parser.get_switch(\"existing\") ? open_file_buffer(name, flags)\n : open_or_create_file_buffer(name, flags);\n if (buffer->flags() & Buffer::Flags::New)\n context.print_status({ format(\"new file '{}'\", name),\n context.faces()[\"StatusLine\"] });\n }\n\n buffer->flags() &= ~Buffer::Flags::NoHooks;\n if (parser.get_switch(\"readonly\"))\n {\n buffer->flags() |= Buffer::Flags::ReadOnly;\n buffer->options()[\"readonly\"].set(true);\n }\n }\n\n Buffer* current_buffer = context.has_buffer() ? &context.buffer() : nullptr;\n\n const size_t param_count = parser.positional_count();\n if (current_buffer and (buffer != current_buffer or param_count > 1))\n context.push_jump();\n\n if (buffer != current_buffer)\n context.change_buffer(*buffer);\n buffer = &context.buffer(); \/\/ change_buffer hooks might change the buffer again\n\n if (parser.get_switch(\"fifo\") and not parser.get_switch(\"scroll\"))\n context.selections_write_only() = { *buffer, Selection{} };\n else if (param_count > 1 and not parser[1].empty())\n {\n int line = std::max(0, str_to_int(parser[1]) - 1);\n int column = param_count > 2 and not parser[2].empty() ?\n std::max(0, str_to_int(parser[2]) - 1) : 0;\n\n auto& buffer = context.buffer();\n context.selections_write_only() = { buffer, buffer.clamp({ line, column }) };\n if (context.has_window())\n context.window().center_line(context.selections().main().cursor().line);\n }\n}\n\nParameterDesc edit_params{\n { { \"existing\", { false, \"fail if the file does not exist, do not open a new file\" } },\n { \"scratch\", { false, \"create a scratch buffer, not linked to a file\" } },\n { \"debug\", { false, \"create buffer as debug output\" } },\n { \"fifo\", { true, \"create a buffer reading its content from a named fifo\" } },\n { \"readonly\", { false, \"create a buffer in readonly mode\" } },\n { \"scroll\", { false, \"place the initial cursor so that the fifo will scroll to show new data\" } } },\n ParameterDesc::Flags::None, 0, 3\n};\nconst CommandDesc edit_cmd = {\n \"edit\",\n \"e\",\n \"edit [] [ []]: open the given filename in a buffer\",\n edit_params,\n CommandFlags::None,\n CommandHelper{},\n filename_completer,\n edit\n};\n\nconst CommandDesc force_edit_cmd = {\n \"edit!\",\n \"e!\",\n \"edit! [] [ []]: open the given filename in a buffer, \"\n \"force reload if needed\",\n edit_params,\n CommandFlags::None,\n CommandHelper{},\n filename_completer,\n edit\n};\n\nconst ParameterDesc write_params{\n {\n { \"sync\", { false, \"force the synchronization of the file onto the filesystem\" } },\n { \"method\", { true, \"explicit writemethod (replace|overwrite)\" } },\n },\n ParameterDesc::Flags::SwitchesOnlyAtStart, 0, 1\n};\n\nauto parse_write_method(StringView str)\n{\n constexpr auto desc = enum_desc(Meta::Type{});\n auto it = find_if(desc, [str](const EnumDesc& d) { return d.name == str; });\n if (it == desc.end())\n throw runtime_error(format(\"invalid writemethod '{}'\", str));\n return it->value;\n}\n\nvoid do_write_buffer(Context& context, Optional filename, WriteFlags flags, Optional write_method = {})\n{\n Buffer& buffer = context.buffer();\n const bool is_file = (bool)(buffer.flags() & Buffer::Flags::File);\n\n if (not filename and !is_file)\n throw runtime_error(\"cannot write a non file buffer without a filename\");\n\n const bool is_readonly = (bool)(context.buffer().flags() & Buffer::Flags::ReadOnly);\n \/\/ if the buffer is in read-only mode and we try to save it directly\n \/\/ or we try to write to it indirectly using e.g. a symlink, throw an error\n if (is_file and is_readonly and\n (not filename or real_path(*filename) == buffer.name()))\n throw runtime_error(\"cannot overwrite the buffer when in readonly mode\");\n\n auto effective_filename = not filename ? buffer.name() : parse_filename(*filename);\n auto method = write_method.value_or_compute([&] { return context.options()[\"writemethod\"].get(); });\n\n context.hooks().run_hook(Hook::BufWritePre, effective_filename, context);\n write_buffer_to_file(buffer, effective_filename, method, flags);\n context.hooks().run_hook(Hook::BufWritePost, effective_filename, context);\n}\n\ntemplate\nvoid write_buffer(const ParametersParser& parser, Context& context, const ShellContext&)\n{\n return do_write_buffer(context,\n parser.positional_count() > 0 ? parser[0] : Optional{},\n (parser.get_switch(\"sync\") ? WriteFlags::Sync : WriteFlags::None) |\n (force ? WriteFlags::Force : WriteFlags::None),\n parser.get_switch(\"method\").map(parse_write_method));\n}\n\nconst CommandDesc write_cmd = {\n \"write\",\n \"w\",\n \"write [] []: write the current buffer to its file \"\n \"or to if specified\",\n write_params,\n CommandFlags::None,\n CommandHelper{},\n filename_completer,\n write_buffer,\n};\n\nconst CommandDesc force_write_cmd = {\n \"write!\",\n \"w!\",\n \"write! [] []: write the current buffer to its file \"\n \"or to if specified, even when the file is write protected\",\n write_params,\n CommandFlags::None,\n CommandHelper{},\n filename_completer,\n write_buffer,\n};\n\nvoid write_all_buffers(const Context& context, bool sync = false, Optional write_method = {})\n{\n \/\/ Copy buffer list because hooks might be creating\/deleting buffers\n Vector> buffers;\n for (auto& buffer : BufferManager::instance())\n buffers.emplace_back(buffer.get());\n\n for (auto& buffer : buffers)\n {\n if ((buffer->flags() & Buffer::Flags::File) and\n ((buffer->flags() & Buffer::Flags::New) or\n buffer->is_modified())\n and !(buffer->flags() & Buffer::Flags::ReadOnly))\n {\n auto method = write_method.value_or_compute([&] { return context.options()[\"writemethod\"].get(); });\n auto flags = sync ? WriteFlags::Sync : WriteFlags::None;\n buffer->run_hook_in_own_context(Hook::BufWritePre, buffer->name(), context.name());\n write_buffer_to_file(*buffer, buffer->name(), method, flags);\n buffer->run_hook_in_own_context(Hook::BufWritePost, buffer->name(), context.name());\n }\n }\n}\n\nconst CommandDesc write_all_cmd = {\n \"write-all\",\n \"wa\",\n \"write-all []: write all changed buffers that are associated to a file\",\n ParameterDesc{\n write_params.switches,\n ParameterDesc::Flags::None, 0, 0\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&){\n write_all_buffers(context,\n (bool)parser.get_switch(\"sync\"),\n parser.get_switch(\"method\").map(parse_write_method));\n }\n};\n\nstatic void ensure_all_buffers_are_saved()\n{\n auto is_modified = [](const std::unique_ptr& buf) {\n return (buf->flags() & Buffer::Flags::File) and buf->is_modified();\n };\n\n auto it = find_if(BufferManager::instance(), is_modified);\n const auto end = BufferManager::instance().end();\n if (it == end)\n return;\n\n String message = format(\"{} modified buffers remaining: [\",\n std::count_if(it, end, is_modified));\n while (it != end)\n {\n message += (*it)->name();\n it = std::find_if(it+1, end, is_modified);\n message += (it != end) ? \", \" : \"]\";\n }\n throw runtime_error(message);\n}\n\ntemplate\nvoid kill(const ParametersParser& parser, Context& context, const ShellContext&)\n{\n auto& client_manager = ClientManager::instance();\n\n if (not force)\n ensure_all_buffers_are_saved();\n\n const int status = parser.positional_count() > 0 ? str_to_int(parser[0]) : 0;\n while (not client_manager.empty())\n client_manager.remove_client(**client_manager.begin(), true, status);\n\n throw kill_session{status};\n}\n\nconst CommandDesc kill_cmd = {\n \"kill\",\n nullptr,\n \"kill []: terminate the current session, the server and all clients connected. \"\n \"An optional integer parameter can set the server and client processes exit status\",\n { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n kill\n};\n\n\nconst CommandDesc force_kill_cmd = {\n \"kill!\",\n nullptr,\n \"kill! []: force the termination of the current session, the server and all clients connected. \"\n \"An optional integer parameter can set the server and client processes exit status\",\n { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n kill\n};\n\ntemplate\nvoid quit(const ParametersParser& parser, Context& context, const ShellContext&)\n{\n if (not force and ClientManager::instance().count() == 1 and not Server::instance().is_daemon())\n ensure_all_buffers_are_saved();\n\n const int status = parser.positional_count() > 0 ? str_to_int(parser[0]) : 0;\n ClientManager::instance().remove_client(context.client(), true, status);\n}\n\nconst CommandDesc quit_cmd = {\n \"quit\",\n \"q\",\n \"quit []: quit current client, and the kakoune session if the client is the last \"\n \"(if not running in daemon mode). \"\n \"An optional integer parameter can set the client exit status\",\n { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n quit\n};\n\nconst CommandDesc force_quit_cmd = {\n \"quit!\",\n \"q!\",\n \"quit! []: quit current client, and the kakoune session if the client is the last \"\n \"(if not running in daemon mode). Force quit even if the client is the \"\n \"last and some buffers are not saved. \"\n \"An optional integer parameter can set the client exit status\",\n { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n quit\n};\n\ntemplate\nvoid write_quit(const ParametersParser& parser, Context& context,\n const ShellContext& shell_context)\n{\n do_write_buffer(context, {},\n parser.get_switch(\"sync\") ? WriteFlags::Sync : WriteFlags::None,\n parser.get_switch(\"method\").map(parse_write_method));\n quit(parser, context, shell_context);\n}\n\nconst CommandDesc write_quit_cmd = {\n \"write-quit\",\n \"wq\",\n \"write-quit [-sync] []: write current buffer and quit current client. \"\n \"An optional integer parameter can set the client exit status\",\n write_params,\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n write_quit\n};\n\nconst CommandDesc force_write_quit_cmd = {\n \"write-quit!\",\n \"wq!\",\n \"write-quit! [-sync] [] write: current buffer and quit current client, even if other buffers are not saved. \"\n \"An optional integer parameter can set the client exit status\",\n write_params,\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n write_quit\n};\n\nconst CommandDesc write_all_quit_cmd = {\n \"write-all-quit\",\n \"waq\",\n \"write-all-quit [-sync] []: write all buffers associated to a file and quit current client. \"\n \"An optional integer parameter can set the client exit status.\",\n write_params,\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)\n {\n write_all_buffers(context,\n (bool)parser.get_switch(\"sync\"),\n parser.get_switch(\"method\").map(parse_write_method));\n quit(parser, context, shell_context);\n }\n};\n\nconst CommandDesc buffer_cmd = {\n \"buffer\",\n \"b\",\n \"buffer : set buffer to edit in current client\",\n single_param,\n CommandFlags::None,\n CommandHelper{},\n make_completer(menu(complete_buffer_name)),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n Buffer& buffer = BufferManager::instance().get_buffer(parser[0]);\n if (&buffer != &context.buffer())\n {\n context.push_jump();\n context.change_buffer(buffer);\n }\n }\n};\n\ntemplate\nvoid cycle_buffer(const ParametersParser& parser, Context& context, const ShellContext&)\n{\n Buffer* oldbuf = &context.buffer();\n auto it = find_if(BufferManager::instance(),\n [oldbuf](const std::unique_ptr& lhs)\n { return lhs.get() == oldbuf; });\n kak_assert(it != BufferManager::instance().end());\n\n Buffer* newbuf = nullptr;\n auto cycle = [&] {\n if (not next)\n {\n if (it == BufferManager::instance().begin())\n it = BufferManager::instance().end();\n --it;\n }\n else\n {\n if (++it == BufferManager::instance().end())\n it = BufferManager::instance().begin();\n }\n newbuf = it->get();\n };\n cycle();\n while (newbuf != oldbuf and newbuf->flags() & Buffer::Flags::Debug)\n cycle();\n\n if (newbuf != oldbuf)\n {\n context.push_jump();\n context.change_buffer(*newbuf);\n }\n}\n\nconst CommandDesc buffer_next_cmd = {\n \"buffer-next\",\n \"bn\",\n \"buffer-next: move to the next buffer in the list\",\n no_params,\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n cycle_buffer\n};\n\nconst CommandDesc buffer_previous_cmd = {\n \"buffer-previous\",\n \"bp\",\n \"buffer-previous: move to the previous buffer in the list\",\n no_params,\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n cycle_buffer\n};\n\ntemplate\nvoid delete_buffer(const ParametersParser& parser, Context& context, const ShellContext&)\n{\n BufferManager& manager = BufferManager::instance();\n Buffer& buffer = parser.positional_count() == 0 ? context.buffer() : manager.get_buffer(parser[0]);\n if (not force and (buffer.flags() & Buffer::Flags::File) and buffer.is_modified())\n throw runtime_error(format(\"buffer '{}' is modified\", buffer.name()));\n\n manager.delete_buffer(buffer);\n context.forget_buffer(buffer);\n}\n\nconst CommandDesc delete_buffer_cmd = {\n \"delete-buffer\",\n \"db\",\n \"delete-buffer [name]: delete current buffer or the buffer named if given\",\n single_optional_param,\n CommandFlags::None,\n CommandHelper{},\n make_completer(menu(complete_buffer_name)),\n delete_buffer\n};\n\nconst CommandDesc force_delete_buffer_cmd = {\n \"delete-buffer!\",\n \"db!\",\n \"delete-buffer! [name]: delete current buffer or the buffer named if \"\n \"given, even if the buffer is unsaved\",\n single_optional_param,\n CommandFlags::None,\n CommandHelper{},\n make_completer(menu(complete_buffer_name)),\n delete_buffer\n};\n\nconst CommandDesc rename_buffer_cmd = {\n \"rename-buffer\",\n nullptr,\n \"rename-buffer : change current buffer name\",\n ParameterDesc{\n {\n { \"scratch\", { false, \"convert a file buffer to a scratch buffer\" } },\n { \"file\", { false, \"convert a scratch buffer to a file buffer\" } }\n },\n ParameterDesc::Flags::None, 1, 1\n },\n CommandFlags::None,\n CommandHelper{},\n filename_completer,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n if (parser.get_switch(\"scratch\") and parser.get_switch(\"file\"))\n throw runtime_error(\"scratch and file are incompatible switches\");\n\n auto& buffer = context.buffer();\n if (parser.get_switch(\"scratch\"))\n buffer.flags() &= ~(Buffer::Flags::File | Buffer::Flags::New);\n if (parser.get_switch(\"file\"))\n buffer.flags() |= Buffer::Flags::File;\n\n if (not buffer.set_name(parser[0]))\n throw runtime_error(format(\"unable to change buffer name to '{}': a buffer with this name already exists\", parser[0]));\n }\n};\n\nstatic constexpr auto highlighter_scopes = { \"global\/\", \"buffer\/\", \"window\/\", \"shared\/\" };\n\ntemplate\nCompletions highlighter_cmd_completer(\n const Context& context, CompletionFlags flags, CommandParameters params,\n size_t token_to_complete, ByteCount pos_in_token)\n{\n if (token_to_complete == 0)\n {\n\n StringView path = params[0];\n auto sep_it = find(path, '\/');\n if (sep_it == path.end())\n return { 0_byte, pos_in_token, complete(path, pos_in_token, highlighter_scopes) };\n\n StringView scope{path.begin(), sep_it};\n HighlighterGroup* root = nullptr;\n if (scope == \"shared\")\n root = &SharedHighlighters::instance();\n else if (auto* s = get_scope_ifp(scope, context))\n root = &s->highlighters().group();\n else\n return {};\n\n auto offset = scope.length() + 1;\n return offset_pos(root->complete_child(StringView{sep_it+1, path.end()}, pos_in_token - offset, add), offset);\n }\n else if (add and token_to_complete == 1)\n {\n StringView name = params[1];\n return { 0_byte, name.length(), complete(name, pos_in_token, HighlighterRegistry::instance() | transform(&HighlighterRegistry::Item::key)) };\n }\n else\n return {};\n}\n\nHighlighter& get_highlighter(const Context& context, StringView path)\n{\n if (not path.empty() and path.back() == '\/')\n path = path.substr(0_byte, path.length() - 1);\n\n auto sep_it = find(path, '\/');\n StringView scope{path.begin(), sep_it};\n auto* root = (scope == \"shared\") ? static_cast(&SharedHighlighters::instance())\n : static_cast(&get_scope(scope, context).highlighters().group());\n if (sep_it != path.end())\n return root->get_child(StringView{sep_it+1, path.end()});\n return *root;\n}\n\nstatic void redraw_relevant_clients(Context& context, StringView highlighter_path)\n{\n StringView scope{highlighter_path.begin(), find(highlighter_path, '\/')};\n if (scope == \"window\")\n context.window().force_redraw();\n else if (scope == \"buffer\" or prefix_match(scope, \"buffer=\"))\n {\n auto& buffer = scope == \"buffer\" ? context.buffer() : BufferManager::instance().get_buffer(scope.substr(7_byte));\n for (auto&& client : ClientManager::instance())\n {\n if (&client->context().buffer() == &buffer)\n client->context().window().force_redraw();\n }\n }\n else\n {\n for (auto&& client : ClientManager::instance())\n client->context().window().force_redraw();\n }\n}\n\nconst CommandDesc arrange_buffers_cmd = {\n \"arrange-buffers\",\n nullptr,\n \"arrange-buffers ...: reorder the buffers in the buffers list\\n\"\n \" the named buffers will be moved to the front of the buffer list, in the order given\\n\"\n \" buffers that do not appear in the parameters will remain at the end of the list, keeping their current order\",\n ParameterDesc{{}, ParameterDesc::Flags::None, 1},\n CommandFlags::None,\n CommandHelper{},\n [](const Context& context, CompletionFlags flags, CommandParameters params, size_t, ByteCount cursor_pos)\n {\n return complete_buffer_name(context, flags, params.back(), cursor_pos);\n },\n [](const ParametersParser& parser, Context&, const ShellContext&)\n {\n BufferManager::instance().arrange_buffers(parser.positionals_from(0));\n }\n};\n\nconst CommandDesc add_highlighter_cmd = {\n \"add-highlighter\",\n \"addhl\",\n \"add-highlighter \/ ...: add an highlighter to the group identified by \\n\"\n \" is a '\/' delimited path or the parent highlighter, starting with either\\n\"\n \" 'global', 'buffer', 'window' or 'shared', if is empty, it will be autogenerated\",\n ParameterDesc{\n { { \"override\", { false, \"replace existing highlighter with same path if it exists\" } }, },\n ParameterDesc::Flags::SwitchesOnlyAtStart, 2\n },\n CommandFlags::None,\n [](const Context& context, CommandParameters params) -> String\n {\n if (params.size() > 1)\n {\n HighlighterRegistry& registry = HighlighterRegistry::instance();\n auto it = registry.find(params[1]);\n if (it != registry.end())\n return format(\"{}:\\n{}\", params[1], indent(it->value.docstring));\n }\n return \"\";\n },\n highlighter_cmd_completer,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n HighlighterRegistry& registry = HighlighterRegistry::instance();\n\n auto begin = parser.begin();\n StringView path = *begin++;\n StringView type = *begin++;\n Vector highlighter_params;\n for (; begin != parser.end(); ++begin)\n highlighter_params.push_back(*begin);\n\n auto it = registry.find(type);\n if (it == registry.end())\n throw runtime_error(format(\"no such highlighter type: '{}'\", type));\n\n auto slash = find(path | reverse(), '\/');\n if (slash == path.rend())\n throw runtime_error(\"no parent in path\");\n\n auto auto_name = [](ConstArrayView params) {\n return join(params | transform([](StringView s) { return replace(s, \"\/\", \"\"); }), \"_\");\n };\n\n String name{slash.base(), path.end()};\n Highlighter& parent = get_highlighter(context, {path.begin(), slash.base() - 1});\n parent.add_child(name.empty() ? auto_name(parser.positionals_from(1)) : std::move(name),\n it->value.factory(highlighter_params, &parent), (bool)parser.get_switch(\"override\"));\n\n redraw_relevant_clients(context, path);\n }\n};\n\nconst CommandDesc remove_highlighter_cmd = {\n \"remove-highlighter\",\n \"rmhl\",\n \"remove-highlighter : remove highlighter identified by \",\n single_param,\n CommandFlags::None,\n CommandHelper{},\n highlighter_cmd_completer,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n StringView path = parser[0];\n if (not path.empty() and path.back() == '\/') \/\/ ignore trailing \/\n path = path.substr(0_byte, path.length() - 1_byte);\n\n auto rev_path = path | reverse();\n auto sep_it = find(rev_path, '\/');\n if (sep_it == rev_path.end())\n return;\n get_highlighter(context, {path.begin(), sep_it.base()}).remove_child({sep_it.base(), path.end()});\n redraw_relevant_clients(context, path);\n }\n};\n\nstatic Completions complete_hooks(const Context&, CompletionFlags,\n const String& prefix, ByteCount cursor_pos)\n{\n return { 0_byte, cursor_pos, complete(prefix, cursor_pos, enum_desc(Meta::Type{}) | transform(&EnumDesc::name)) };\n}\n\nconst CommandDesc add_hook_cmd = {\n \"hook\",\n nullptr,\n \"hook [] : add in \"\n \"to be executed on hook when its parameter matches the regex\\n\"\n \" can be:\\n\"\n \" * global: hook is executed for any buffer or window\\n\"\n \" * buffer: hook is executed only for the current buffer\\n\"\n \" (and any window for that buffer)\\n\"\n \" * window: hook is executed only for the current window\\n\",\n ParameterDesc{\n { { \"group\", { true, \"set hook group, see remove-hooks\" } },\n { \"always\", { false, \"run hook even if hooks are disabled\" } },\n { \"once\", { false, \"run the hook only once\" } } },\n ParameterDesc::Flags::None, 4, 4\n },\n CommandFlags::None,\n CommandHelper{},\n make_completer(complete_scope, complete_hooks, complete_nothing,\n [](const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos)\n { return CommandManager::instance().complete(\n context, flags, prefix, cursor_pos); }),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n auto descs = enum_desc(Meta::Type{});\n auto it = find_if(descs, [&](const EnumDesc& desc) { return desc.name == parser[1]; });\n if (it == descs.end())\n throw runtime_error{format(\"no such hook: '{}'\", parser[1])};\n\n Regex regex{parser[2], RegexCompileFlags::Optimize};\n const String& command = parser[3];\n auto group = parser.get_switch(\"group\").value_or(StringView{});\n\n if (any_of(group, [](char c) { return not is_word(c, { '-' }); }) or\n (not group.empty() and not is_word(group[0])))\n throw runtime_error{format(\"invalid group name '{}'\", group)};\n\n const auto flags = (parser.get_switch(\"always\") ? HookFlags::Always : HookFlags::None) |\n (parser.get_switch(\"once\") ? HookFlags::Once : HookFlags::None);\n get_scope(parser[0], context).hooks().add_hook(it->value, group.str(), flags,\n std::move(regex), command);\n }\n};\n\nconst CommandDesc remove_hook_cmd = {\n \"remove-hooks\",\n \"rmhooks\",\n \"remove-hooks : remove all hooks whose group matches the regex \",\n double_params,\n CommandFlags::None,\n CommandHelper{},\n [](const Context& context, CompletionFlags flags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token) -> Completions\n {\n if (token_to_complete == 0)\n return { 0_byte, params[0].length(),\n complete(params[0], pos_in_token, scopes) };\n else if (token_to_complete == 1)\n {\n if (auto scope = get_scope_ifp(params[0], context))\n return { 0_byte, params[0].length(),\n scope->hooks().complete_hook_group(params[1], pos_in_token) };\n }\n return {};\n },\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n get_scope(parser[0], context).hooks().remove_hooks(Regex{parser[1]});\n }\n};\n\nconst CommandDesc trigger_user_hook_cmd = {\n \"trigger-user-hook\",\n nullptr,\n \"trigger-user-hook : run 'User' hook with as filter string\",\n single_param,\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n context.hooks().run_hook(Hook::User, parser[0], context);\n }\n};\n\nVector params_to_shell(const ParametersParser& parser)\n{\n Vector vars;\n for (size_t i = 0; i < parser.positional_count(); ++i)\n vars.push_back(parser[i]);\n return vars;\n}\n\nvoid define_command(const ParametersParser& parser, Context& context, const ShellContext&)\n{\n const String& cmd_name = parser[0];\n auto& cm = CommandManager::instance();\n\n if (not all_of(cmd_name, is_identifier))\n throw runtime_error(format(\"invalid command name: '{}'\", cmd_name));\n\n if (cm.command_defined(cmd_name) and not parser.get_switch(\"override\"))\n throw runtime_error(format(\"command '{}' already defined\", cmd_name));\n\n CommandFlags flags = CommandFlags::None;\n if (parser.get_switch(\"hidden\"))\n flags = CommandFlags::Hidden;\n\n const Completions::Flags completions_flags = parser.get_switch(\"menu\") ?\n Completions::Flags::Menu : Completions::Flags::None;\n\n const String& commands = parser[1];\n CommandFunc cmd;\n ParameterDesc desc;\n if (auto params = parser.get_switch(\"params\"))\n {\n size_t min = 0, max = -1;\n StringView counts = *params;\n static const Regex re{R\"((\\d+)?..(\\d+)?)\"};\n MatchResults res;\n if (regex_match(counts.begin(), counts.end(), res, re))\n {\n if (res[1].matched)\n min = (size_t)str_to_int({res[1].first, res[1].second});\n if (res[2].matched)\n max = (size_t)str_to_int({res[2].first, res[2].second});\n }\n else\n min = max = (size_t)str_to_int(counts);\n\n desc = ParameterDesc{ {}, ParameterDesc::Flags::SwitchesAsPositional, min, max };\n cmd = [=](const ParametersParser& parser, Context& context, const ShellContext& sc) {\n CommandManager::instance().execute(commands, context,\n { params_to_shell(parser), sc.env_vars });\n };\n }\n else\n {\n desc = ParameterDesc{ {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 0 };\n cmd = [=](const ParametersParser& parser, Context& context, const ShellContext& sc) {\n CommandManager::instance().execute(commands, context, { {}, sc.env_vars });\n };\n }\n\n CommandCompleter completer;\n if (parser.get_switch(\"file-completion\"))\n {\n completer = [=](const Context& context, CompletionFlags flags,\n CommandParameters params,\n size_t token_to_complete, ByteCount pos_in_token)\n {\n const String& prefix = params[token_to_complete];\n const auto& ignored_files = context.options()[\"ignored_files\"].get();\n return Completions{0_byte, pos_in_token,\n complete_filename(prefix, ignored_files,\n pos_in_token, FilenameFlags::Expand),\n completions_flags};\n };\n }\n else if (parser.get_switch(\"client-completion\"))\n {\n completer = [=](const Context& context, CompletionFlags flags,\n CommandParameters params,\n size_t token_to_complete, ByteCount pos_in_token)\n {\n const String& prefix = params[token_to_complete];\n auto& cm = ClientManager::instance();\n return Completions{0_byte, pos_in_token,\n cm.complete_client_name(prefix, pos_in_token),\n completions_flags};\n };\n }\n else if (parser.get_switch(\"buffer-completion\"))\n {\n completer = [=](const Context& context, CompletionFlags flags,\n CommandParameters params,\n size_t token_to_complete, ByteCount pos_in_token)\n {\n return add_flags(complete_buffer_name, completions_flags)(\n context, flags, params[token_to_complete], pos_in_token);\n };\n }\n else if (auto shell_script = parser.get_switch(\"shell-script-completion\"))\n {\n completer = ShellScriptCompleter{shell_script->str(), completions_flags};\n }\n else if (auto shell_script = parser.get_switch(\"shell-script-candidates\"))\n {\n completer = ShellCandidatesCompleter{shell_script->str(), completions_flags};\n }\n else if (parser.get_switch(\"command-completion\"))\n {\n completer = [](const Context& context, CompletionFlags flags,\n CommandParameters params,\n size_t token_to_complete, ByteCount pos_in_token)\n {\n return CommandManager::instance().complete(\n context, flags, params, token_to_complete, pos_in_token);\n };\n }\n else if (parser.get_switch(\"shell-completion\"))\n {\n completer = [=](const Context& context, CompletionFlags flags,\n CommandParameters params,\n size_t token_to_complete, ByteCount pos_in_token)\n {\n return add_flags(shell_complete, completions_flags)(\n context, flags, params[token_to_complete], pos_in_token);\n };\n }\n\n auto docstring = trim_indent(parser.get_switch(\"docstring\").value_or(StringView{}));\n\n cm.register_command(cmd_name, cmd, docstring, desc, flags, CommandHelper{}, completer);\n}\n\nconst CommandDesc define_command_cmd = {\n \"define-command\",\n \"def\",\n \"define-command [] : define a command executing \",\n ParameterDesc{\n { { \"params\", { true, \"take parameters, accessible to each shell escape as $0..$N\\n\"\n \"parameter should take the form or .. (both omittable)\" } },\n { \"override\", { false, \"allow overriding an existing command\" } },\n { \"hidden\", { false, \"do not display the command in completion candidates\" } },\n { \"docstring\", { true, \"define the documentation string for command\" } },\n { \"menu\", { false, \"treat completions as the only valid inputs\" } },\n { \"file-completion\", { false, \"complete parameters using filename completion\" } },\n { \"client-completion\", { false, \"complete parameters using client name completion\" } },\n { \"buffer-completion\", { false, \"complete parameters using buffer name completion\" } },\n { \"command-completion\", { false, \"complete parameters using kakoune command completion\" } },\n { \"shell-completion\", { false, \"complete parameters using shell command completion\" } },\n { \"shell-script-completion\", { true, \"complete parameters using the given shell-script\" } },\n { \"shell-script-candidates\", { true, \"get the parameter candidates using the given shell-script\" } } },\n ParameterDesc::Flags::None,\n 2, 2\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n define_command\n};\n\nconst CommandDesc alias_cmd = {\n \"alias\",\n nullptr,\n \"alias : alias to in \",\n ParameterDesc{{}, ParameterDesc::Flags::None, 3, 3},\n CommandFlags::None,\n CommandHelper{},\n make_completer(complete_scope, complete_nothing, complete_command_name),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n if (not CommandManager::instance().command_defined(parser[2]))\n throw runtime_error(format(\"no such command: '{}'\", parser[2]));\n\n AliasRegistry& aliases = get_scope(parser[0], context).aliases();\n aliases.add_alias(parser[1], parser[2]);\n }\n};\n\nstatic Completions complete_alias(const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos)\n{\n return {0_byte, cursor_pos,\n complete(prefix, cursor_pos, context.aliases().flatten_aliases() |\n transform([](auto& entry) -> const String& { return entry.key; }))};\n}\n\nconst CommandDesc unalias_cmd = {\n \"unalias\",\n nullptr,\n \"unalias []: remove from \\n\"\n \"If is specified, remove only if its value is \",\n ParameterDesc{{}, ParameterDesc::Flags::None, 2, 3},\n CommandFlags::None,\n CommandHelper{},\n make_completer(complete_scope, complete_alias, complete_command_name),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n AliasRegistry& aliases = get_scope(parser[0], context).aliases();\n if (parser.positional_count() == 3 and\n aliases[parser[1]] != parser[2])\n return;\n aliases.remove_alias(parser[1]);\n }\n};\n\nconst CommandDesc echo_cmd = {\n \"echo\",\n nullptr,\n \"echo ...: display given parameters in the status line\",\n ParameterDesc{\n { { \"markup\", { false, \"parse markup\" } },\n { \"quoting\", { true, \"quote each argument separately using the given style (raw|kakoune|shell)\" } },\n { \"to-file\", { true, \"echo contents to given filename\" } },\n { \"debug\", { false, \"write to debug buffer instead of status line\" } } },\n ParameterDesc::Flags::SwitchesOnlyAtStart\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n String message;\n if (auto quoting = parser.get_switch(\"quoting\"))\n message = join(parser | transform(quoter(option_from_string(Meta::Type{}, *quoting))),\n ' ', false);\n else\n message = join(parser, ' ', false);\n\n if (auto filename = parser.get_switch(\"to-file\"))\n return write_to_file(*filename, message);\n\n message = fix_atom_text(message);\n if (parser.get_switch(\"debug\"))\n write_to_debug_buffer(message);\n else if (parser.get_switch(\"markup\"))\n context.print_status(parse_display_line(message, context.faces()));\n else\n context.print_status({replace(message, '\\t', ' '), context.faces()[\"StatusLine\"]});\n }\n};\n\nKeymapMode parse_keymap_mode(StringView str, const KeymapManager::UserModeList& user_modes)\n{\n if (prefix_match(\"normal\", str)) return KeymapMode::Normal;\n if (prefix_match(\"insert\", str)) return KeymapMode::Insert;\n if (prefix_match(\"menu\", str)) return KeymapMode::Menu;\n if (prefix_match(\"prompt\", str)) return KeymapMode::Prompt;\n if (prefix_match(\"goto\", str)) return KeymapMode::Goto;\n if (prefix_match(\"view\", str)) return KeymapMode::View;\n if (prefix_match(\"user\", str)) return KeymapMode::User;\n if (prefix_match(\"object\", str)) return KeymapMode::Object;\n\n auto it = find(user_modes, str);\n if (it == user_modes.end())\n throw runtime_error(format(\"no such keymap mode: '{}'\", str));\n\n char offset = static_cast(KeymapMode::FirstUserMode);\n return (KeymapMode)(std::distance(user_modes.begin(), it) + offset);\n}\n\nstatic constexpr auto modes = { \"normal\", \"insert\", \"menu\", \"prompt\", \"goto\", \"view\", \"user\", \"object\" };\n\nconst CommandDesc debug_cmd = {\n \"debug\",\n nullptr,\n \"debug : write some debug information to the *debug* buffer\",\n ParameterDesc{{}, ParameterDesc::Flags::SwitchesOnlyAtStart, 1},\n CommandFlags::None,\n CommandHelper{},\n make_completer(\n [](const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos) -> Completions {\n auto c = {\"info\", \"buffers\", \"options\", \"memory\", \"shared-strings\",\n \"profile-hash-maps\", \"faces\", \"mappings\", \"regex\", \"registers\"};\n return { 0_byte, cursor_pos, complete(prefix, cursor_pos, c) };\n }),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n if (parser[0] == \"info\")\n {\n write_to_debug_buffer(format(\"version: {}\", version));\n write_to_debug_buffer(format(\"pid: {}\", getpid()));\n write_to_debug_buffer(format(\"session: {}\", Server::instance().session()));\n #ifdef KAK_DEBUG\n write_to_debug_buffer(\"build: debug\");\n #else\n write_to_debug_buffer(\"build: release\");\n #endif\n }\n else if (parser[0] == \"buffers\")\n {\n write_to_debug_buffer(\"Buffers:\");\n for (auto& buffer : BufferManager::instance())\n write_to_debug_buffer(buffer->debug_description());\n }\n else if (parser[0] == \"options\")\n {\n write_to_debug_buffer(\"Options:\");\n for (auto& option : context.options().flatten_options())\n write_to_debug_buffer(format(\" * {}: {}\", option->name(),\n option->get_as_string(Quoting::Kakoune)));\n }\n else if (parser[0] == \"memory\")\n {\n auto total = 0;\n write_to_debug_buffer(\"Memory usage:\");\n const ColumnCount column_size = 13;\n write_to_debug_buffer(format(\"{} \u2502{} \u2502{} \u2502{} \",\n left_pad(\"domain\", column_size),\n left_pad(\"bytes\", column_size),\n left_pad(\"active allocs\", column_size),\n left_pad(\"total allocs\", column_size)));\n write_to_debug_buffer(format(\"{0}\u253c{0}\u253c{0}\u253c{0}\", String(Codepoint{0x2500}, column_size + 1)));\n\n for (int domain = 0; domain < (int)MemoryDomain::Count; ++domain)\n {\n auto& stats = memory_stats[domain];\n total += stats.allocated_bytes;\n write_to_debug_buffer(format(\"{} \u2502{} \u2502{} \u2502{} \",\n left_pad(domain_name((MemoryDomain)domain), column_size),\n left_pad(to_string(stats.allocated_bytes), column_size),\n left_pad(to_string(stats.allocation_count), column_size),\n left_pad(to_string(stats.total_allocation_count), column_size)));\n }\n write_to_debug_buffer({});\n write_to_debug_buffer(format(\" Total: {}\", total));\n #if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 33))\n write_to_debug_buffer(format(\" Malloced: {}\", mallinfo2().uordblks));\n #elif defined(__GLIBC__) || defined(__CYGWIN__)\n write_to_debug_buffer(format(\" Malloced: {}\", mallinfo().uordblks));\n #endif\n }\n else if (parser[0] == \"shared-strings\")\n {\n StringRegistry::instance().debug_stats();\n }\n else if (parser[0] == \"profile-hash-maps\")\n {\n profile_hash_maps();\n }\n else if (parser[0] == \"faces\")\n {\n write_to_debug_buffer(\"Faces:\");\n for (auto& face : context.faces().flatten_faces())\n write_to_debug_buffer(format(\" * {}: {}\", face.key, face.value.face));\n }\n else if (parser[0] == \"mappings\")\n {\n auto& keymaps = context.keymaps();\n auto user_modes = keymaps.user_modes();\n write_to_debug_buffer(\"Mappings:\");\n for (auto& mode : concatenated(modes, user_modes) | gather>())\n {\n KeymapMode m = parse_keymap_mode(mode, user_modes);\n for (auto& key : keymaps.get_mapped_keys(m))\n write_to_debug_buffer(format(\" * {} {}: {}\",\n mode, key_to_str(key),\n keymaps.get_mapping(key, m).docstring));\n }\n }\n else if (parser[0] == \"regex\")\n {\n if (parser.positional_count() != 2)\n throw runtime_error(\"expected a regex\");\n\n write_to_debug_buffer(format(\" * {}:\\n{}\",\n parser[1], dump_regex(compile_regex(parser[1], RegexCompileFlags::Optimize))));\n }\n else if (parser[0] == \"registers\")\n {\n write_to_debug_buffer(\"Register info:\");\n for (auto&& [name, reg] : RegisterManager::instance())\n {\n auto content = reg->get(context);\n\n if (content.size() == 1 and content[0] == \"\")\n continue;\n\n write_to_debug_buffer(format(\" * {} = {}\\n\", name,\n join(content | transform(quote), \"\\n = \")));\n }\n }\n else\n throw runtime_error(format(\"no such debug command: '{}'\", parser[0]));\n }\n};\n\nconst CommandDesc source_cmd = {\n \"source\",\n nullptr,\n \"source ...: execute commands contained in \\n\"\n \"parameters are available in the sourced script as %arg{0}, %arg{1}, \u2026\",\n ParameterDesc{ {}, ParameterDesc::Flags::None, 1, (size_t)-1 },\n CommandFlags::None,\n CommandHelper{},\n filename_completer,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n const DebugFlags debug_flags = context.options()[\"debug\"].get();\n const bool profile = debug_flags & DebugFlags::Profile;\n auto start_time = profile ? Clock::now() : Clock::time_point{};\n\n String path = real_path(parse_filename(parser[0]));\n MappedFile file_content{path};\n try\n {\n auto params = parser | skip(1) | gather>();\n CommandManager::instance().execute(file_content, context,\n {params, {{\"source\", path}}});\n }\n catch (Kakoune::runtime_error& err)\n {\n write_to_debug_buffer(format(\"{}:{}\", parser[0], err.what()));\n throw;\n }\n\n using namespace std::chrono;\n if (profile)\n write_to_debug_buffer(format(\"sourcing '{}' took {} us\", parser[0],\n (size_t)duration_cast(Clock::now() - start_time).count()));\n }\n};\n\nstatic String option_doc_helper(const Context& context, CommandParameters params)\n{\n const bool add = params.size() > 1 and params[0] == \"-add\";\n if (params.size() < 2 + (add ? 1 : 0))\n return \"\";\n\n auto desc = GlobalScope::instance().option_registry().option_desc(params[1 + (add ? 1 : 0)]);\n if (not desc or desc->docstring().empty())\n return \"\";\n\n return format(\"{}:\\n{}\", desc->name(), indent(desc->docstring()));\n}\n\nstatic OptionManager& get_options(StringView scope, const Context& context, StringView option_name)\n{\n if (scope == \"current\")\n return context.options()[option_name].manager();\n return get_scope(scope, context).options();\n}\n\nconst CommandDesc set_option_cmd = {\n \"set-option\",\n \"set\",\n \"set-option [] : set option in to \\n\"\n \" can be global, buffer, window, or current which refers to the narrowest \"\n \"scope the option is set in\",\n ParameterDesc{\n { { \"add\", { false, \"add to option rather than replacing it\" } },\n { \"remove\", { false, \"remove from option rather than replacing it\" } } },\n ParameterDesc::Flags::SwitchesOnlyAtStart, 2, (size_t)-1\n },\n CommandFlags::None,\n option_doc_helper,\n [](const Context& context, CompletionFlags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token) -> Completions\n {\n const bool add = params.size() > 1 and params[0] == \"-add\";\n const int start = add ? 1 : 0;\n\n static constexpr auto scopes = { \"global\", \"buffer\", \"window\", \"current\" };\n\n if (token_to_complete == start)\n return { 0_byte, params[start].length(),\n complete(params[start], pos_in_token, scopes) };\n else if (token_to_complete == start + 1)\n return { 0_byte, params[start + 1].length(),\n GlobalScope::instance().option_registry().complete_option_name(params[start + 1], pos_in_token) };\n else if (not add and token_to_complete == start + 2 and params[start + 2].empty() and\n GlobalScope::instance().option_registry().option_exists(params[start + 1]))\n {\n OptionManager& options = get_scope(params[start], context).options();\n return {0_byte, params[start + 2].length(),\n {options[params[start + 1]].get_as_string(Quoting::Kakoune)},\n Completions::Flags::Quoted};\n }\n return Completions{};\n },\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n bool add = (bool)parser.get_switch(\"add\");\n bool remove = (bool)parser.get_switch(\"remove\");\n if (add and remove)\n throw runtime_error(\"cannot add and remove at the same time\");\n\n Option& opt = get_options(parser[0], context, parser[1]).get_local_option(parser[1]);\n if (add)\n opt.add_from_strings(parser.positionals_from(2));\n else if (remove)\n opt.remove_from_strings(parser.positionals_from(2));\n else\n opt.set_from_strings(parser.positionals_from(2));\n }\n};\n\nCompletions complete_option(const Context& context, CompletionFlags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token)\n{\n if (token_to_complete == 0)\n {\n static constexpr auto scopes = { \"buffer\", \"window\", \"current\" };\n return { 0_byte, params[0].length(), complete(params[0], pos_in_token, scopes) };\n }\n else if (token_to_complete == 1)\n return { 0_byte, params[1].length(),\n GlobalScope::instance().option_registry().complete_option_name(params[1], pos_in_token) };\n return Completions{};\n}\n\nconst CommandDesc unset_option_cmd = {\n \"unset-option\",\n \"unset\",\n \"unset-option : remove option from scope, falling back on parent scope value\\n\"\n \" can be buffer, window, or current which refers to the narrowest \"\n \"scope the option is set in\",\n double_params,\n CommandFlags::None,\n option_doc_helper,\n complete_option,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n auto& options = get_options(parser[0], context, parser[1]);\n if (&options == &GlobalScope::instance().options())\n throw runtime_error(\"cannot unset options in global scope\");\n options.unset_option(parser[1]);\n }\n};\n\nconst CommandDesc update_option_cmd = {\n \"update-option\",\n nullptr,\n \"update-option : update option from scope\\n\"\n \"some option types, such as line-specs or range-specs can be updated to latest buffer timestamp\\n\"\n \" can be buffer, window, or current which refers to the narrowest \"\n \"scope the option is set in\",\n double_params,\n CommandFlags::None,\n option_doc_helper,\n complete_option,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n Option& opt = get_options(parser[0], context, parser[1]).get_local_option(parser[1]);\n opt.update(context);\n }\n};\n\nconst CommandDesc declare_option_cmd = {\n \"declare-option\",\n \"decl\",\n \"declare-option [] [value]: declare option of type .\\n\"\n \"set its initial value to if given and the option did not exist\\n\"\n \"Available types:\\n\"\n \" int: integer\\n\"\n \" bool: boolean (true\/false or yes\/no)\\n\"\n \" str: character string\\n\"\n \" regex: regular expression\\n\"\n \" int-list: list of integers\\n\"\n \" str-list: list of character strings\\n\"\n \" completions: list of completion candidates\\n\"\n \" line-specs: list of line specs\\n\"\n \" range-specs: list of range specs\\n\"\n \" str-to-str-map: map from strings to strings\\n\",\n ParameterDesc{\n { { \"hidden\", { false, \"do not display option name when completing\" } },\n { \"docstring\", { true, \"specify option description\" } } },\n ParameterDesc::Flags::SwitchesOnlyAtStart, 2, (size_t)-1\n },\n CommandFlags::None,\n CommandHelper{},\n make_completer(\n [](const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos) -> Completions {\n auto c = {\"int\", \"bool\", \"str\", \"regex\", \"int-list\", \"str-list\", \"completions\", \"line-specs\", \"range-specs\", \"str-to-str-map\"};\n return { 0_byte, cursor_pos, complete(prefix, cursor_pos, c) };\n }),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n Option* opt = nullptr;\n\n OptionFlags flags = OptionFlags::None;\n if (parser.get_switch(\"hidden\"))\n flags = OptionFlags::Hidden;\n\n auto docstring = trim_indent(parser.get_switch(\"docstring\").value_or(StringView{}));\n OptionsRegistry& reg = GlobalScope::instance().option_registry();\n\n\n if (parser[0] == \"int\")\n opt = ®.declare_option(parser[1], docstring, 0, flags);\n else if (parser[0] == \"bool\")\n opt = ®.declare_option(parser[1], docstring, false, flags);\n else if (parser[0] == \"str\")\n opt = ®.declare_option(parser[1], docstring, \"\", flags);\n else if (parser[0] == \"regex\")\n opt = ®.declare_option(parser[1], docstring, Regex{}, flags);\n else if (parser[0] == \"int-list\")\n opt = ®.declare_option>(parser[1], docstring, {}, flags);\n else if (parser[0] == \"str-list\")\n opt = ®.declare_option>(parser[1], docstring, {}, flags);\n else if (parser[0] == \"completions\")\n opt = ®.declare_option(parser[1], docstring, {}, flags);\n else if (parser[0] == \"line-specs\")\n opt = ®.declare_option>(parser[1], docstring, {}, flags);\n else if (parser[0] == \"range-specs\")\n opt = ®.declare_option>(parser[1], docstring, {}, flags);\n else if (parser[0] == \"str-to-str-map\")\n opt = ®.declare_option>(parser[1], docstring, {}, flags);\n else\n throw runtime_error(format(\"no such option type: '{}'\", parser[0]));\n\n if (parser.positional_count() > 2)\n opt->set_from_strings(parser.positionals_from(2));\n }\n};\n\ntemplate\nstatic Completions map_key_completer(const Context& context, CompletionFlags flags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token)\n{\n if (token_to_complete == 0)\n return { 0_byte, params[0].length(),\n complete(params[0], pos_in_token, scopes) };\n if (token_to_complete == 1)\n {\n auto& user_modes = get_scope(params[0], context).keymaps().user_modes();\n return { 0_byte, params[1].length(),\n complete(params[1], pos_in_token, concatenated(modes, user_modes) | gather>()) };\n }\n if (unmap and token_to_complete == 2)\n {\n KeymapManager& keymaps = get_scope(params[0], context).keymaps();\n KeymapMode keymap_mode = parse_keymap_mode(params[1], keymaps.user_modes());\n KeyList keys = keymaps.get_mapped_keys(keymap_mode);\n\n return { 0_byte, params[2].length(),\n complete(params[2], pos_in_token,\n keys | transform([](Key k) { return key_to_str(k); })\n | gather>()) };\n }\n return {};\n}\n\nconst CommandDesc map_key_cmd = {\n \"map\",\n nullptr,\n \"map [] : map to in given in \",\n ParameterDesc{\n { { \"docstring\", { true, \"specify mapping description\" } } },\n ParameterDesc::Flags::None, 4, 4\n },\n CommandFlags::None,\n CommandHelper{},\n map_key_completer,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n KeymapManager& keymaps = get_scope(parser[0], context).keymaps();\n KeymapMode keymap_mode = parse_keymap_mode(parser[1], keymaps.user_modes());\n\n KeyList key = parse_keys(parser[2]);\n if (key.size() != 1)\n throw runtime_error(\"only a single key can be mapped\");\n\n KeyList mapping = parse_keys(parser[3]);\n keymaps.map_key(key[0], keymap_mode, std::move(mapping),\n trim_indent(parser.get_switch(\"docstring\").value_or(\"\")));\n }\n};\n\nconst CommandDesc unmap_key_cmd = {\n \"unmap\",\n nullptr,\n \"unmap [ []]: unmap from given in .\\n\"\n \"If is specified, remove the mapping only if its value is .\\n\"\n \"If only and are specified remove all mappings\",\n ParameterDesc{{}, ParameterDesc::Flags::None, 2, 4},\n CommandFlags::None,\n CommandHelper{},\n map_key_completer,\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n KeymapManager& keymaps = get_scope(parser[0], context).keymaps();\n KeymapMode keymap_mode = parse_keymap_mode(parser[1], keymaps.user_modes());\n\n if (parser.positional_count() == 2)\n {\n keymaps.unmap_keys(keymap_mode);\n return;\n }\n\n KeyList key = parse_keys(parser[2]);\n if (key.size() != 1)\n throw runtime_error(\"only a single key can be unmapped\");\n\n if (keymaps.is_mapped(key[0], keymap_mode) and\n (parser.positional_count() < 4 or\n (keymaps.get_mapping(key[0], keymap_mode).keys ==\n parse_keys(parser[3]))))\n keymaps.unmap_key(key[0], keymap_mode);\n }\n};\n\ntemplate\nParameterDesc make_context_wrap_params_impl(Array, sizeof...(P)>&& additional_params,\n std::index_sequence)\n{\n return { { { \"client\", { true, \"run in given client context\" } },\n { \"try-client\", { true, \"run in given client context if it exists, or else in the current one\" } },\n { \"buffer\", { true, \"run in a disposable context for each given buffer in the comma separated list argument\" } },\n { \"draft\", { false, \"run in a disposable context\" } },\n { \"itersel\", { false, \"run once for each selection with that selection as the only one\" } },\n { \"save-regs\", { true, \"restore all given registers after execution\" } },\n std::move(additional_params[P])...},\n ParameterDesc::Flags::SwitchesOnlyAtStart, 1\n };\n}\n\ntemplate\nParameterDesc make_context_wrap_params(Array, N>&& additional_params)\n{\n return make_context_wrap_params_impl(std::move(additional_params), std::make_index_sequence());\n}\n\ntemplate\nvoid context_wrap(const ParametersParser& parser, Context& context, StringView default_saved_regs, Func func)\n{\n if ((int)(bool)parser.get_switch(\"buffer\") +\n (int)(bool)parser.get_switch(\"client\") +\n (int)(bool)parser.get_switch(\"try-client\") > 1)\n throw runtime_error{\"only one of -buffer, -client or -try-client can be specified\"};\n\n const auto& register_manager = RegisterManager::instance();\n auto make_register_restorer = [&](char c) {\n auto& reg = register_manager[c];\n return on_scope_end([&, c, save=reg.save(context), d=ScopedSetBool{reg.modified_hook_disabled()}] {\n try\n {\n reg.restore(context, save);\n }\n catch (runtime_error& err)\n {\n write_to_debug_buffer(format(\"failed to restore register '{}': {}\", c, err.what()));\n }\n });\n };\n Vector saved_registers;\n for (auto c : parser.get_switch(\"save-regs\").value_or(default_saved_regs))\n saved_registers.push_back(make_register_restorer(c));\n\n if (auto bufnames = parser.get_switch(\"buffer\"))\n {\n auto context_wrap_for_buffer = [&](Buffer& buffer) {\n InputHandler input_handler{{ buffer, Selection{} },\n Context::Flags::Draft};\n Context& c = input_handler.context();\n\n ScopedSetBool disable_history(c.history_disabled());\n\n func(parser, c);\n };\n if (*bufnames == \"*\")\n {\n for (auto&& buffer : BufferManager::instance()\n | transform(&std::unique_ptr::get)\n | filter([](Buffer* buf) { return not (buf->flags() & Buffer::Flags::Debug); })\n | gather>>()) \/\/ gather as we might be mutating the buffer list in the loop.\n context_wrap_for_buffer(*buffer);\n }\n else\n for (auto&& name : *bufnames | split(','))\n context_wrap_for_buffer(BufferManager::instance().get_buffer(name));\n return;\n }\n\n ClientManager& cm = ClientManager::instance();\n Context* base_context = &context;\n if (auto client_name = parser.get_switch(\"client\"))\n base_context = &cm.get_client(*client_name).context();\n else if (auto client_name = parser.get_switch(\"try-client\"))\n {\n if (Client* client = cm.get_client_ifp(*client_name))\n base_context = &client->context();\n }\n\n Optional input_handler;\n Context* effective_context = base_context;\n\n const bool draft = (bool)parser.get_switch(\"draft\");\n if (draft)\n {\n input_handler.emplace(base_context->selections(),\n Context::Flags::Draft,\n base_context->name());\n effective_context = &input_handler->context();\n\n \/\/ Preserve window so that window scope is available\n if (base_context->has_window())\n effective_context->set_window(base_context->window());\n\n \/\/ We do not want this draft context to commit undo groups if the real one is\n \/\/ going to commit the whole thing later\n if (base_context->is_editing())\n effective_context->disable_undo_handling();\n }\n\n Context& c = *effective_context;\n\n ScopedSetBool disable_history(c.history_disabled());\n ScopedEdition edition{c};\n\n if (parser.get_switch(\"itersel\"))\n {\n SelectionList sels{base_context->selections()};\n Vector new_sels;\n size_t main = 0;\n size_t timestamp = c.buffer().timestamp();\n bool one_selection_succeeded = false;\n for (auto& sel : sels)\n {\n c.selections_write_only() = SelectionList{sels.buffer(), sel, sels.timestamp()};\n c.selections().update();\n\n try\n {\n func(parser, c);\n one_selection_succeeded = true;\n\n if (&sels.buffer() != &c.buffer())\n throw runtime_error(\"buffer has changed while iterating on selections\");\n\n if (not draft)\n {\n update_selections(new_sels, main, c.buffer(), timestamp);\n timestamp = c.buffer().timestamp();\n if (&sel == &sels.main())\n main = new_sels.size() + c.selections().main_index();\n\n const auto middle = new_sels.insert(new_sels.end(), c.selections().begin(), c.selections().end());\n std::inplace_merge(new_sels.begin(), middle, new_sels.end(), compare_selections);\n }\n }\n catch (no_selections_remaining&) {}\n }\n\n if (not one_selection_succeeded)\n {\n c.selections_write_only() = std::move(sels);\n throw no_selections_remaining{};\n }\n\n if (not draft)\n c.selections_write_only().set(std::move(new_sels), main);\n }\n else\n {\n const bool collapse_jumps = not (c.flags() & Context::Flags::Draft) and context.has_buffer();\n auto& jump_list = c.jump_list();\n const size_t prev_index = jump_list.current_index();\n auto jump = collapse_jumps ? c.selections() : Optional{};\n\n func(parser, c);\n\n \/\/ If the jump list got mutated, collapse all jumps into a single one from original selections\n if (auto index = jump_list.current_index();\n collapse_jumps and index > prev_index and\n contains(BufferManager::instance(), &jump->buffer()))\n jump_list.push(std::move(*jump), prev_index);\n }\n}\n\nconst CommandDesc execute_keys_cmd = {\n \"execute-keys\",\n \"exec\",\n \"execute-keys [] : execute given keys as if entered by user\",\n make_context_wrap_params<2>({{\n {\"with-maps\", {false, \"use user defined key mapping when executing keys\"}},\n {\"with-hooks\", {false, \"trigger hooks while executing keys\"}}\n }}),\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n context_wrap(parser, context, \"\/\\\"|^@:\", [](const ParametersParser& parser, Context& context) {\n ScopedSetBool disable_keymaps(context.keymaps_disabled(), not parser.get_switch(\"with-maps\"));\n ScopedSetBool disable_hoooks(context.hooks_disabled(), not parser.get_switch(\"with-hooks\"));\n\n KeyList keys;\n for (auto& param : parser)\n {\n KeyList param_keys = parse_keys(param);\n keys.insert(keys.end(), param_keys.begin(), param_keys.end());\n }\n\n for (auto& key : keys)\n context.input_handler().handle_key(key);\n });\n }\n};\n\nconst CommandDesc evaluate_commands_cmd = {\n \"evaluate-commands\",\n \"eval\",\n \"evaluate-commands [] ...: execute commands as if entered by user\",\n make_context_wrap_params<2>({{\n {\"no-hooks\", { false, \"disable hooks while executing commands\" }},\n {\"verbatim\", { false, \"do not reparse argument\" }}\n }}),\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)\n {\n context_wrap(parser, context, {}, [&](const ParametersParser& parser, Context& context) {\n const bool no_hooks = context.hooks_disabled() or parser.get_switch(\"no-hooks\");\n ScopedSetBool disable_hoooks(context.hooks_disabled(), no_hooks);\n\n if (parser.get_switch(\"verbatim\"))\n CommandManager::instance().execute_single_command(parser | gather(), context, shell_context);\n else\n CommandManager::instance().execute(join(parser, ' ', false), context, shell_context);\n });\n }\n};\n\nstruct CapturedShellContext\n{\n explicit CapturedShellContext(const ShellContext& sc)\n : params{sc.params.begin(), sc.params.end()}, env_vars{sc.env_vars} {}\n\n Vector params;\n EnvVarMap env_vars;\n\n operator ShellContext() const { return { params, env_vars }; }\n};\n\nconst CommandDesc prompt_cmd = {\n \"prompt\",\n nullptr,\n \"prompt [] : prompt the user to enter a text string \"\n \"and then executes , entered text is available in the 'text' value\",\n ParameterDesc{\n { { \"init\", { true, \"set initial prompt content\" } },\n { \"password\", { false, \"Do not display entered text and clear reg after command\" } },\n { \"file-completion\", { false, \"use file completion for prompt\" } },\n { \"client-completion\", { false, \"use client completion for prompt\" } },\n { \"buffer-completion\", { false, \"use buffer completion for prompt\" } },\n { \"command-completion\", { false, \"use command completion for prompt\" } },\n { \"shell-completion\", { false, \"use shell command completion for prompt\" } },\n { \"shell-script-completion\", { true, \"use shell command completion for prompt\" } },\n { \"shell-script-candidates\", { true, \"use shell command completion for prompt\" } },\n { \"on-change\", { true, \"command to execute whenever the prompt changes\" } },\n { \"on-abort\", { true, \"command to execute whenever the prompt is canceled\" } } },\n ParameterDesc::Flags::None, 2, 2\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)\n {\n const String& command = parser[1];\n auto initstr = parser.get_switch(\"init\").value_or(StringView{});\n\n PromptCompleter completer;\n if (parser.get_switch(\"file-completion\"))\n completer = [](const Context& context, CompletionFlags,\n StringView prefix, ByteCount cursor_pos) -> Completions {\n auto& ignored_files = context.options()[\"ignored_files\"].get();\n return { 0_byte, cursor_pos,\n complete_filename(prefix, ignored_files, cursor_pos,\n FilenameFlags::Expand) };\n };\n else if (parser.get_switch(\"client-completion\"))\n completer = [](const Context& context, CompletionFlags,\n StringView prefix, ByteCount cursor_pos) -> Completions {\n return { 0_byte, cursor_pos,\n ClientManager::instance().complete_client_name(prefix, cursor_pos) };\n };\n else if (parser.get_switch(\"buffer-completion\"))\n completer = complete_buffer_name;\n else if (parser.get_switch(\"command-completion\"))\n completer = [](const Context& context, CompletionFlags flags,\n StringView prefix, ByteCount cursor_pos) -> Completions {\n return CommandManager::instance().complete(\n context, flags, prefix, cursor_pos);\n };\n else if (parser.get_switch(\"shell-completion\"))\n completer = shell_complete;\n else if (auto shell_script = parser.get_switch(\"shell-script-completion\"))\n completer = PromptCompleterAdapter{ShellScriptCompleter{shell_script->str()}};\n else if (auto shell_script = parser.get_switch(\"shell-script-candidates\"))\n completer = PromptCompleterAdapter{ShellCandidatesCompleter{shell_script->str()}};\n\n const auto flags = parser.get_switch(\"password\") ?\n PromptFlags::Password : PromptFlags::None;\n\n context.input_handler().prompt(\n parser[0], initstr.str(), {}, context.faces()[\"Prompt\"],\n flags, '_', std::move(completer),\n [command,\n on_change = parser.get_switch(\"on-change\").value_or(\"\").str(),\n on_abort = parser.get_switch(\"on-abort\").value_or(\"\").str(),\n sc = CapturedShellContext{shell_context}]\n (StringView str, PromptEvent event, Context& context) mutable\n {\n if ((event == PromptEvent::Abort and on_abort.empty()) or\n (event == PromptEvent::Change and on_change.empty()))\n return;\n\n sc.env_vars[\"text\"_sv] = String{String::NoCopy{}, str};\n auto remove_text = on_scope_end([&] {\n sc.env_vars.erase(\"text\"_sv);\n });\n\n ScopedSetBool disable_history{context.history_disabled()};\n\n StringView cmd;\n switch (event)\n {\n case PromptEvent::Validate: cmd = command; break;\n case PromptEvent::Change: cmd = on_change; break;\n case PromptEvent::Abort: cmd = on_abort; break;\n }\n try\n {\n CommandManager::instance().execute(cmd, context, sc);\n }\n catch (Kakoune::runtime_error& error)\n {\n context.print_status({fix_atom_text(error.what()), context.faces()[\"Error\"]});\n context.hooks().run_hook(Hook::RuntimeError, error.what(), context);\n }\n });\n }\n};\n\nconst CommandDesc menu_cmd = {\n \"menu\",\n nullptr,\n \"menu [] ...: display a \"\n \"menu and execute commands for the selected item\",\n ParameterDesc{\n { { \"auto-single\", { false, \"instantly validate if only one item is available\" } },\n { \"select-cmds\", { false, \"each item specify an additional command to run when selected\" } },\n { \"markup\", { false, \"parse menu entries as markup text\" } } }\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)\n {\n const bool with_select_cmds = (bool)parser.get_switch(\"select-cmds\");\n const bool markup = (bool)parser.get_switch(\"markup\");\n const size_t modulo = with_select_cmds ? 3 : 2;\n\n const size_t count = parser.positional_count();\n if (count == 0 or (count % modulo) != 0)\n throw wrong_argument_count();\n\n if (count == modulo and parser.get_switch(\"auto-single\"))\n {\n ScopedSetBool disable_history{context.history_disabled()};\n\n CommandManager::instance().execute(parser[1], context);\n return;\n }\n\n Vector choices;\n Vector commands;\n Vector select_cmds;\n for (int i = 0; i < count; i += modulo)\n {\n if (parser[i].empty())\n throw runtime_error(format(\"entry #{} is empty\", i+1));\n\n choices.push_back(markup ? parse_display_line(parser[i], context.faces())\n : DisplayLine{ parser[i], {} });\n commands.push_back(parser[i+1]);\n if (with_select_cmds)\n select_cmds.push_back(parser[i+2]);\n }\n\n CapturedShellContext sc{shell_context};\n context.input_handler().menu(std::move(choices),\n [=](int choice, MenuEvent event, Context& context) {\n ScopedSetBool disable_history{context.history_disabled()};\n\n if (event == MenuEvent::Validate and choice >= 0 and choice < commands.size())\n CommandManager::instance().execute(commands[choice], context, sc);\n if (event == MenuEvent::Select and choice >= 0 and choice < select_cmds.size())\n CommandManager::instance().execute(select_cmds[choice], context, sc);\n });\n }\n};\n\nconst CommandDesc on_key_cmd = {\n \"on-key\",\n nullptr,\n \"on-key : wait for next user key and then execute , \"\n \"with key available in the `key` value\",\n ParameterDesc{\n { { \"mode-name\", { true, \"set mode name to use\" } } },\n ParameterDesc::Flags::None, 1, 1\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)\n {\n String command = parser[0];\n\n CapturedShellContext sc{shell_context};\n context.input_handler().on_next_key(\n parser.get_switch(\"mode-name\").value_or(\"on-key\"),\n KeymapMode::None, [=](Key key, Context& context) mutable {\n sc.env_vars[\"key\"_sv] = key_to_str(key);\n ScopedSetBool disable_history{context.history_disabled()};\n\n CommandManager::instance().execute(command, context, sc);\n });\n }\n};\n\nconst CommandDesc info_cmd = {\n \"info\",\n nullptr,\n \"info [] : display an info box containing \",\n ParameterDesc{\n { { \"anchor\", { true, \"set info anchoring .\" } },\n { \"style\", { true, \"set info style (above, below, menu, modal)\" } },\n { \"markup\", { false, \"parse markup\" } },\n { \"title\", { true, \"set info title\" } } },\n ParameterDesc::Flags::None, 0, 1\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n if (not context.has_client())\n return;\n\n const InfoStyle style = parser.get_switch(\"style\").map(\n [](StringView style) -> Optional {\n if (style == \"above\") return InfoStyle::InlineAbove;\n if (style == \"below\") return InfoStyle::InlineBelow;\n if (style == \"menu\") return InfoStyle::MenuDoc;\n if (style == \"modal\") return InfoStyle::Modal;\n throw runtime_error(format(\"invalid style: '{}'\", style));\n }).value_or(parser.get_switch(\"anchor\") ? InfoStyle::Inline : InfoStyle::Prompt);\n\n context.client().info_hide(style == InfoStyle::Modal);\n if (parser.positional_count() == 0)\n return;\n\n const BufferCoord pos = parser.get_switch(\"anchor\").map(\n [](StringView anchor) {\n auto dot = find(anchor, '.');\n if (dot == anchor.end())\n throw runtime_error(\"expected . for anchor\");\n\n return BufferCoord{str_to_int({anchor.begin(), dot})-1,\n str_to_int({dot+1, anchor.end()})-1};\n }).value_or(BufferCoord{});\n\n auto title = parser.get_switch(\"title\").value_or(StringView{});\n if (parser.get_switch(\"markup\"))\n context.client().info_show(parse_display_line(title, context.faces()),\n parser[0] | split('\\n')\n | transform([&](StringView s) {\n return parse_display_line(s, context.faces());\n })\n | gather(),\n pos, style);\n else\n context.client().info_show(title.str(), parser[0], pos, style);\n }\n};\n\nconst CommandDesc try_catch_cmd = {\n \"try\",\n nullptr,\n \"try [catch ]...: execute in current context.\\n\"\n \"if an error is raised and is specified, execute it and do\\n\"\n \"not propagate that error. If raises an error and another\\n\"\n \" is provided, execute this one and so-on\\n\",\n ParameterDesc{{}, ParameterDesc::Flags::None, 1},\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)\n {\n if ((parser.positional_count() % 2) != 1)\n throw wrong_argument_count();\n\n for (size_t i = 1; i < parser.positional_count(); i += 2)\n {\n if (parser[i] != \"catch\")\n throw runtime_error(\"usage: try [catch ]...\");\n }\n\n CommandManager& command_manager = CommandManager::instance();\n Optional shell_context_with_error;\n for (size_t i = 0; i < parser.positional_count(); i += 2)\n {\n if (i == 0 or i < parser.positional_count() - 1)\n {\n try\n {\n command_manager.execute(parser[i], context,\n shell_context_with_error.value_or(shell_context));\n return;\n }\n catch (const runtime_error& error)\n {\n shell_context_with_error.emplace(shell_context);\n shell_context_with_error->env_vars[StringView{\"error\"}] = error.what().str();\n }\n }\n else\n command_manager.execute(parser[i], context,\n shell_context_with_error.value_or(shell_context));\n }\n }\n};\n\nstatic Completions complete_face(const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos)\n{\n return {0_byte, cursor_pos,\n complete(prefix, cursor_pos, context.faces().flatten_faces() |\n transform([](auto& entry) -> const String& { return entry.key; }))};\n}\n\nstatic String face_doc_helper(const Context& context, CommandParameters params)\n{\n if (params.size() < 2)\n return {};\n try\n {\n auto face = context.faces()[params[1]];\n return format(\"{}:\\n{}\", params[1], indent(to_string(face)));\n }\n catch (runtime_error&)\n {\n return {};\n }\n}\n\nconst CommandDesc set_face_cmd = {\n \"set-face\",\n \"face\",\n \"set-face : set face to refer to in \\n\"\n \"\\n\"\n \"facespec format is [,][+][@]\\n\"\n \"colors are either a color name, rgb:######, or rgba:######## values.\\n\"\n \"attributes is a combination of:\\n\"\n \" u: underline, i: italic, b: bold, r: reverse,\\n\"\n \" B: blink, d: dim,\\n\"\n \" f: final foreground, g: final background,\\n\"\n \" a: final attributes, F: same as +fga\\n\"\n \"facespec can as well just be the name of another face.\\n\"\n \"if a base face is specified, colors and attributes are applied on top of it\",\n ParameterDesc{{}, ParameterDesc::Flags::None, 3, 3},\n CommandFlags::None,\n face_doc_helper,\n make_completer(complete_scope, complete_face, complete_face),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n get_scope(parser[0], context).faces().add_face(parser[1], parser[2], true);\n\n for (auto& client : ClientManager::instance())\n client->force_redraw();\n }\n};\n\nconst CommandDesc unset_face_cmd = {\n \"unset-face\",\n nullptr,\n \"unset-face : remove from \",\n double_params,\n CommandFlags::None,\n face_doc_helper,\n make_completer(complete_scope, complete_face),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n get_scope(parser[0], context).faces().remove_face(parser[1]);\n }\n};\n\nconst CommandDesc rename_client_cmd = {\n \"rename-client\",\n nullptr,\n \"rename-client : set current client name to \",\n single_param,\n CommandFlags::None,\n CommandHelper{},\n make_single_word_completer([](const Context& context){ return context.name(); }),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n const String& name = parser[0];\n if (not all_of(name, is_identifier))\n throw runtime_error{format(\"invalid client name: '{}'\", name)};\n else if (ClientManager::instance().client_name_exists(name) and\n context.name() != name)\n throw runtime_error{format(\"client name '{}' is not unique\", name)};\n else\n context.set_name(name);\n }\n};\n\nconst CommandDesc set_register_cmd = {\n \"set-register\",\n \"reg\",\n \"set-register ...: set register to \",\n ParameterDesc{{}, ParameterDesc::Flags::SwitchesAsPositional, 1},\n CommandFlags::None,\n CommandHelper{},\n make_completer(\n [](const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos) -> Completions {\n return { 0_byte, cursor_pos,\n RegisterManager::instance().complete_register_name(prefix, cursor_pos) };\n }),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n RegisterManager::instance()[parser[0]].set(context, parser.positionals_from(1));\n }\n};\n\nconst CommandDesc select_cmd = {\n \"select\",\n nullptr,\n \"select ...: select given selections\\n\"\n \"\\n\"\n \"selection_desc format is .,.\",\n ParameterDesc{{\n {\"timestamp\", {true, \"specify buffer timestamp at which those selections are valid\"}},\n {\"codepoint\", {false, \"columns are specified in codepoints, not bytes\"}},\n {\"display-column\", {false, \"columns are specified in display columns, not bytes\"}}\n },\n ParameterDesc::Flags::SwitchesOnlyAtStart, 1\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n auto& buffer = context.buffer();\n const size_t timestamp = parser.get_switch(\"timestamp\").map(str_to_int_ifp).cast().value_or(buffer.timestamp());\n ColumnType column_type = ColumnType::Byte;\n if (parser.get_switch(\"codepoint\"))\n column_type = ColumnType::Codepoint;\n else if (parser.get_switch(\"display-column\"))\n column_type = ColumnType::DisplayColumn;\n ColumnCount tabstop = context.options()[\"tabstop\"].get();\n context.selections_write_only() = selection_list_from_strings(buffer, column_type, parser.positionals_from(0), timestamp, 0, tabstop);\n }\n};\n\nconst CommandDesc change_directory_cmd = {\n \"change-directory\",\n \"cd\",\n \"change-directory []: change the server's working directory to , or the home directory if unspecified\",\n single_optional_param,\n CommandFlags::None,\n CommandHelper{},\n make_completer(\n [](const Context& context, CompletionFlags flags,\n const String& prefix, ByteCount cursor_pos) -> Completions {\n return { 0_byte, cursor_pos,\n complete_filename(prefix,\n context.options()[\"ignored_files\"].get(),\n cursor_pos, FilenameFlags::OnlyDirectories) };\n }),\n [](const ParametersParser& parser, Context&, const ShellContext&)\n {\n StringView target = parser.positional_count() == 1 ? StringView{parser[0]} : \"~\";\n if (chdir(parse_filename(target).c_str()) != 0)\n throw runtime_error(format(\"unable to change to directory: '{}'\", target));\n for (auto& buffer : BufferManager::instance())\n buffer->update_display_name();\n }\n};\n\nconst CommandDesc rename_session_cmd = {\n \"rename-session\",\n nullptr,\n \"rename-session : change remote session name\",\n single_param,\n CommandFlags::None,\n CommandHelper{},\n make_single_word_completer([](const Context&){ return Server::instance().session(); }),\n [](const ParametersParser& parser, Context&, const ShellContext&)\n {\n if (not Server::instance().rename_session(parser[0]))\n throw runtime_error(format(\"unable to rename current session: '{}' may be already in use\", parser[0]));\n }\n};\n\nconst CommandDesc fail_cmd = {\n \"fail\",\n nullptr,\n \"fail []: raise an error with the given message\",\n ParameterDesc{},\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context&, const ShellContext&)\n {\n throw failure{fix_atom_text(join(parser, \" \"))};\n }\n};\n\nconst CommandDesc declare_user_mode_cmd = {\n \"declare-user-mode\",\n nullptr,\n \"declare-user-mode : add a new user keymap mode\",\n single_param,\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n context.keymaps().add_user_mode(std::move(parser[0]));\n }\n};\n\n\/\/ We need ownership of the mode_name in the lock case\nvoid enter_user_mode(Context& context, String mode_name, KeymapMode mode, bool lock)\n{\n on_next_key_with_autoinfo(context, format(\"user.{}\", mode_name), KeymapMode::None,\n [mode_name, mode, lock](Key key, Context& context) mutable {\n if (key == Key::Escape)\n return;\n if (not context.keymaps().is_mapped(key, mode))\n return;\n\n auto& mapping = context.keymaps().get_mapping(key, mode);\n ScopedSetBool disable_keymaps(context.keymaps_disabled());\n\n InputHandler::ScopedForceNormal force_normal{context.input_handler(), {}};\n\n ScopedEdition edition(context);\n for (auto& key : mapping.keys)\n context.input_handler().handle_key(key);\n\n if (lock)\n enter_user_mode(context, std::move(mode_name), mode, true);\n }, lock ? format(\"{} (lock)\", mode_name) : mode_name,\n build_autoinfo_for_mapping(context, mode, {}));\n}\n\nconst CommandDesc enter_user_mode_cmd = {\n \"enter-user-mode\",\n nullptr,\n \"enter-user-mode [] : enable keymap mode for next key\",\n ParameterDesc{\n { { \"lock\", { false, \"stay in mode until is pressed\" } } },\n ParameterDesc::Flags::SwitchesOnlyAtStart, 1, 1\n },\n CommandFlags::None,\n CommandHelper{},\n [](const Context& context, CompletionFlags flags,\n CommandParameters params, size_t token_to_complete,\n ByteCount pos_in_token) -> Completions\n {\n if (token_to_complete == 0)\n {\n return { 0_byte, params[0].length(),\n complete(params[0], pos_in_token, context.keymaps().user_modes()) };\n }\n return {};\n },\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n auto lock = (bool)parser.get_switch(\"lock\");\n KeymapMode mode = parse_keymap_mode(parser[0], context.keymaps().user_modes());\n enter_user_mode(context, std::move(parser[0]), mode, lock);\n }\n};\n\nconst CommandDesc provide_module_cmd = {\n \"provide-module\",\n nullptr,\n \"provide-module [] : declares a module provided by \",\n ParameterDesc{\n { { \"override\", { false, \"allow overriding an existing module\" } } },\n ParameterDesc::Flags::None,\n 2, 2\n },\n CommandFlags::None,\n CommandHelper{},\n CommandCompleter{},\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n const String& module_name = parser[0];\n auto& cm = CommandManager::instance();\n\n if (not all_of(module_name, is_identifier))\n throw runtime_error(format(\"invalid module name: '{}'\", module_name));\n\n if (cm.module_defined(module_name) and not parser.get_switch(\"override\"))\n throw runtime_error(format(\"module '{}' already defined\", module_name));\n cm.register_module(module_name, parser[1]);\n }\n};\n\nconst CommandDesc require_module_cmd = {\n \"require-module\",\n nullptr,\n \"require-module : ensures that module has been loaded\",\n single_param,\n CommandFlags::None,\n CommandHelper{},\n make_completer(\n [](const Context&, CompletionFlags, const String& prefix, ByteCount cursor_pos) {\n return CommandManager::instance().complete_module_name(prefix.substr(0, cursor_pos));\n }),\n [](const ParametersParser& parser, Context& context, const ShellContext&)\n {\n CommandManager::instance().load_module(parser[0], context);\n }\n};\n\n}\n\nvoid register_commands()\n{\n CommandManager& cm = CommandManager::instance();\n cm.register_command(\"nop\", [](const ParametersParser&, Context&, const ShellContext&){}, \"do nothing\", {});\n\n auto register_command = [&](const CommandDesc& c)\n {\n cm.register_command(c.name, c.func, c.docstring, c.params, c.flags, c.helper, c.completer);\n if (c.alias)\n GlobalScope::instance().aliases().add_alias(c.alias, c.name);\n };\n\n register_command(edit_cmd);\n register_command(force_edit_cmd);\n register_command(write_cmd);\n register_command(force_write_cmd);\n register_command(write_all_cmd);\n register_command(write_all_quit_cmd);\n register_command(kill_cmd);\n register_command(force_kill_cmd);\n register_command(quit_cmd);\n register_command(force_quit_cmd);\n register_command(write_quit_cmd);\n register_command(force_write_quit_cmd);\n register_command(buffer_cmd);\n register_command(buffer_next_cmd);\n register_command(buffer_previous_cmd);\n register_command(delete_buffer_cmd);\n register_command(force_delete_buffer_cmd);\n register_command(rename_buffer_cmd);\n register_command(arrange_buffers_cmd);\n register_command(add_highlighter_cmd);\n register_command(remove_highlighter_cmd);\n register_command(add_hook_cmd);\n register_command(remove_hook_cmd);\n register_command(trigger_user_hook_cmd);\n register_command(define_command_cmd);\n register_command(alias_cmd);\n register_command(unalias_cmd);\n register_command(echo_cmd);\n register_command(debug_cmd);\n register_command(source_cmd);\n register_command(set_option_cmd);\n register_command(unset_option_cmd);\n register_command(update_option_cmd);\n register_command(declare_option_cmd);\n register_command(map_key_cmd);\n register_command(unmap_key_cmd);\n register_command(execute_keys_cmd);\n register_command(evaluate_commands_cmd);\n register_command(prompt_cmd);\n register_command(menu_cmd);\n register_command(on_key_cmd);\n register_command(info_cmd);\n register_command(try_catch_cmd);\n register_command(set_face_cmd);\n register_command(unset_face_cmd);\n register_command(rename_client_cmd);\n register_command(set_register_cmd);\n register_command(select_cmd);\n register_command(change_directory_cmd);\n register_command(rename_session_cmd);\n register_command(fail_cmd);\n register_command(declare_user_mode_cmd);\n register_command(enter_user_mode_cmd);\n register_command(provide_module_cmd);\n register_command(require_module_cmd);\n}\n\n}\n","avg_line_length":39.3517975055,"max_line_length":149,"alphanum_fraction":0.6083730296} {"size":4682,"ext":"cpp","lang":"C++","max_stars_count":43.0,"content":"\/*\n * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\nusing TencentCloud::CoreInternalOutcome;\nusing namespace TencentCloud::Mariadb::V20170312::Model;\nusing namespace std;\n\nLogFileInfo::LogFileInfo() :\n m_mtimeHasBeenSet(false),\n m_lengthHasBeenSet(false),\n m_uriHasBeenSet(false),\n m_fileNameHasBeenSet(false)\n{\n}\n\nCoreInternalOutcome LogFileInfo::Deserialize(const rapidjson::Value &value)\n{\n string requestId = \"\";\n\n\n if (value.HasMember(\"Mtime\") && !value[\"Mtime\"].IsNull())\n {\n if (!value[\"Mtime\"].IsUint64())\n {\n return CoreInternalOutcome(Core::Error(\"response `LogFileInfo.Mtime` IsUint64=false incorrectly\").SetRequestId(requestId));\n }\n m_mtime = value[\"Mtime\"].GetUint64();\n m_mtimeHasBeenSet = true;\n }\n\n if (value.HasMember(\"Length\") && !value[\"Length\"].IsNull())\n {\n if (!value[\"Length\"].IsUint64())\n {\n return CoreInternalOutcome(Core::Error(\"response `LogFileInfo.Length` IsUint64=false incorrectly\").SetRequestId(requestId));\n }\n m_length = value[\"Length\"].GetUint64();\n m_lengthHasBeenSet = true;\n }\n\n if (value.HasMember(\"Uri\") && !value[\"Uri\"].IsNull())\n {\n if (!value[\"Uri\"].IsString())\n {\n return CoreInternalOutcome(Core::Error(\"response `LogFileInfo.Uri` IsString=false incorrectly\").SetRequestId(requestId));\n }\n m_uri = string(value[\"Uri\"].GetString());\n m_uriHasBeenSet = true;\n }\n\n if (value.HasMember(\"FileName\") && !value[\"FileName\"].IsNull())\n {\n if (!value[\"FileName\"].IsString())\n {\n return CoreInternalOutcome(Core::Error(\"response `LogFileInfo.FileName` IsString=false incorrectly\").SetRequestId(requestId));\n }\n m_fileName = string(value[\"FileName\"].GetString());\n m_fileNameHasBeenSet = true;\n }\n\n\n return CoreInternalOutcome(true);\n}\n\nvoid LogFileInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const\n{\n\n if (m_mtimeHasBeenSet)\n {\n rapidjson::Value iKey(rapidjson::kStringType);\n string key = \"Mtime\";\n iKey.SetString(key.c_str(), allocator);\n value.AddMember(iKey, m_mtime, allocator);\n }\n\n if (m_lengthHasBeenSet)\n {\n rapidjson::Value iKey(rapidjson::kStringType);\n string key = \"Length\";\n iKey.SetString(key.c_str(), allocator);\n value.AddMember(iKey, m_length, allocator);\n }\n\n if (m_uriHasBeenSet)\n {\n rapidjson::Value iKey(rapidjson::kStringType);\n string key = \"Uri\";\n iKey.SetString(key.c_str(), allocator);\n value.AddMember(iKey, rapidjson::Value(m_uri.c_str(), allocator).Move(), allocator);\n }\n\n if (m_fileNameHasBeenSet)\n {\n rapidjson::Value iKey(rapidjson::kStringType);\n string key = \"FileName\";\n iKey.SetString(key.c_str(), allocator);\n value.AddMember(iKey, rapidjson::Value(m_fileName.c_str(), allocator).Move(), allocator);\n }\n\n}\n\n\nuint64_t LogFileInfo::GetMtime() const\n{\n return m_mtime;\n}\n\nvoid LogFileInfo::SetMtime(const uint64_t& _mtime)\n{\n m_mtime = _mtime;\n m_mtimeHasBeenSet = true;\n}\n\nbool LogFileInfo::MtimeHasBeenSet() const\n{\n return m_mtimeHasBeenSet;\n}\n\nuint64_t LogFileInfo::GetLength() const\n{\n return m_length;\n}\n\nvoid LogFileInfo::SetLength(const uint64_t& _length)\n{\n m_length = _length;\n m_lengthHasBeenSet = true;\n}\n\nbool LogFileInfo::LengthHasBeenSet() const\n{\n return m_lengthHasBeenSet;\n}\n\nstring LogFileInfo::GetUri() const\n{\n return m_uri;\n}\n\nvoid LogFileInfo::SetUri(const string& _uri)\n{\n m_uri = _uri;\n m_uriHasBeenSet = true;\n}\n\nbool LogFileInfo::UriHasBeenSet() const\n{\n return m_uriHasBeenSet;\n}\n\nstring LogFileInfo::GetFileName() const\n{\n return m_fileName;\n}\n\nvoid LogFileInfo::SetFileName(const string& _fileName)\n{\n m_fileName = _fileName;\n m_fileNameHasBeenSet = true;\n}\n\nbool LogFileInfo::FileNameHasBeenSet() const\n{\n return m_fileNameHasBeenSet;\n}\n\n","avg_line_length":25.7252747253,"max_line_length":138,"alphanum_fraction":0.6689448953} {"size":103,"ext":"hpp","lang":"C++","max_stars_count":null,"content":"#pragma once\n\n#include \"includes.hpp\"\n\nclass App : public wxApp\n{\npublic:\n virtual bool OnInit();\n};","avg_line_length":11.4444444444,"max_line_length":26,"alphanum_fraction":0.6796116505} {"size":654,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n#include \n#include \n\n#include \n\nnamespace scratch {\n particle::particle(const GLfloat elapsed)\n {\n this->rate = ((float) rand()) \/ ((float) RAND_MAX) * 0.1;\n\n this->x = ((float) rand()) \/ ((float) RAND_MAX);\n this->y = ((float) rand()) \/ ((float) RAND_MAX);\n\n reset(elapsed);\n }\n\n void particle::reset(GLfloat elapsed)\n {\n spawned = elapsed;\n this->z = 0.5f + ((float) rand()) \/ ((float) RAND_MAX);\n }\n\n void particle::update(GLfloat elapsed)\n {\n auto age = elapsed - spawned;\n double distance = age * rate;\n\n z -= distance;\n\n if (z < 0) reset(elapsed);\n }\n}\n","avg_line_length":19.2352941176,"max_line_length":61,"alphanum_fraction":0.5917431193} {"size":192728,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/\/===- Bitcode\/Writer\/BitcodeWriter.cpp - Bitcode Writer ------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Bitcode writer implementation.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bitcode\/BitcodeWriter.h\"\n#include \"ValueEnumerator.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/ADT\/APInt.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/None.h\"\n#include \"llvm\/ADT\/Optional.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Bitcode\/BitcodeCommon.h\"\n#include \"llvm\/Bitcode\/BitcodeReader.h\"\n#include \"llvm\/Bitcode\/LLVMBitCodes.h\"\n#include \"llvm\/Bitstream\/BitCodes.h\"\n#include \"llvm\/Bitstream\/BitstreamWriter.h\"\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/IR\/Attributes.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Comdat.h\"\n#include \"llvm\/IR\/Constant.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/DebugInfoMetadata.h\"\n#include \"llvm\/IR\/DebugLoc.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalAlias.h\"\n#include \"llvm\/IR\/GlobalIFunc.h\"\n#include \"llvm\/IR\/GlobalObject.h\"\n#include \"llvm\/IR\/GlobalValue.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/InlineAsm.h\"\n#include \"llvm\/IR\/InstrTypes.h\"\n#include \"llvm\/IR\/Instruction.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Metadata.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/ModuleSummaryIndex.h\"\n#include \"llvm\/IR\/Operator.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/UseListOrder.h\"\n#include \"llvm\/IR\/Value.h\"\n#include \"llvm\/IR\/ValueSymbolTable.h\"\n#include \"llvm\/MC\/StringTableBuilder.h\"\n#include \"llvm\/Object\/IRSymtab.h\"\n#include \"llvm\/Support\/AtomicOrdering.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Endian.h\"\n#include \"llvm\/Support\/Error.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/SHA1.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace llvm;\n\nstatic cl::opt\n IndexThreshold(\"bitcode-mdindex-threshold\", cl::Hidden, cl::init(25),\n cl::desc(\"Number of metadatas above which we emit an index \"\n \"to enable lazy-loading\"));\nstatic cl::opt FlushThreshold(\n \"bitcode-flush-threshold\", cl::Hidden, cl::init(512),\n cl::desc(\"The threshold (unit M) for flushing LLVM bitcode.\"));\n\nstatic cl::opt WriteRelBFToSummary(\n \"write-relbf-to-summary\", cl::Hidden, cl::init(false),\n cl::desc(\"Write relative block frequency to function summary \"));\n\nextern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;\n\nnamespace {\n\n\/\/\/ These are manifest constants used by the bitcode writer. They do not need to\n\/\/\/ be kept in sync with the reader, but need to be consistent within this file.\nenum {\n \/\/ VALUE_SYMTAB_BLOCK abbrev id's.\n VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,\n VST_ENTRY_7_ABBREV,\n VST_ENTRY_6_ABBREV,\n VST_BBENTRY_6_ABBREV,\n\n \/\/ CONSTANTS_BLOCK abbrev id's.\n CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,\n CONSTANTS_INTEGER_ABBREV,\n CONSTANTS_CE_CAST_Abbrev,\n CONSTANTS_NULL_Abbrev,\n\n \/\/ FUNCTION_BLOCK abbrev id's.\n FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,\n FUNCTION_INST_UNOP_ABBREV,\n FUNCTION_INST_UNOP_FLAGS_ABBREV,\n FUNCTION_INST_BINOP_ABBREV,\n FUNCTION_INST_BINOP_FLAGS_ABBREV,\n FUNCTION_INST_CAST_ABBREV,\n FUNCTION_INST_RET_VOID_ABBREV,\n FUNCTION_INST_RET_VAL_ABBREV,\n FUNCTION_INST_UNREACHABLE_ABBREV,\n FUNCTION_INST_GEP_ABBREV,\n};\n\n\/\/\/ Abstract class to manage the bitcode writing, subclassed for each bitcode\n\/\/\/ file type.\nclass BitcodeWriterBase {\nprotected:\n \/\/\/ The stream created and owned by the client.\n BitstreamWriter &Stream;\n\n StringTableBuilder &StrtabBuilder;\n\npublic:\n \/\/\/ Constructs a BitcodeWriterBase object that writes to the provided\n \/\/\/ \\p Stream.\n BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)\n : Stream(Stream), StrtabBuilder(StrtabBuilder) {}\n\nprotected:\n void writeBitcodeHeader();\n void writeModuleVersion();\n};\n\nvoid BitcodeWriterBase::writeModuleVersion() {\n \/\/ VERSION: [version#]\n Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef{2});\n}\n\n\/\/\/ Base class to manage the module bitcode writing, currently subclassed for\n\/\/\/ ModuleBitcodeWriter and ThinLinkBitcodeWriter.\nclass ModuleBitcodeWriterBase : public BitcodeWriterBase {\nprotected:\n \/\/\/ The Module to write to bitcode.\n const Module &M;\n\n \/\/\/ Enumerates ids for all values in the module.\n ValueEnumerator VE;\n\n \/\/\/ Optional per-module index to write for ThinLTO.\n const ModuleSummaryIndex *Index;\n\n \/\/\/ Map that holds the correspondence between GUIDs in the summary index,\n \/\/\/ that came from indirect call profiles, and a value id generated by this\n \/\/\/ class to use in the VST and summary block records.\n std::map GUIDToValueIdMap;\n\n \/\/\/ Tracks the last value id recorded in the GUIDToValueMap.\n unsigned GlobalValueId;\n\n \/\/\/ Saves the offset of the VSTOffset record that must eventually be\n \/\/\/ backpatched with the offset of the actual VST.\n uint64_t VSTOffsetPlaceholder = 0;\n\npublic:\n \/\/\/ Constructs a ModuleBitcodeWriterBase object for the given Module,\n \/\/\/ writing to the provided \\p Buffer.\n ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,\n BitstreamWriter &Stream,\n bool ShouldPreserveUseListOrder,\n const ModuleSummaryIndex *Index)\n : BitcodeWriterBase(Stream, StrtabBuilder), M(M),\n VE(M, ShouldPreserveUseListOrder), Index(Index) {\n \/\/ Assign ValueIds to any callee values in the index that came from\n \/\/ indirect call profiles and were recorded as a GUID not a Value*\n \/\/ (which would have been assigned an ID by the ValueEnumerator).\n \/\/ The starting ValueId is just after the number of values in the\n \/\/ ValueEnumerator, so that they can be emitted in the VST.\n GlobalValueId = VE.getValues().size();\n if (!Index)\n return;\n for (const auto &GUIDSummaryLists : *Index)\n \/\/ Examine all summaries for this GUID.\n for (auto &Summary : GUIDSummaryLists.second.SummaryList)\n if (auto FS = dyn_cast(Summary.get()))\n \/\/ For each call in the function summary, see if the call\n \/\/ is to a GUID (which means it is for an indirect call,\n \/\/ otherwise we would have a Value for it). If so, synthesize\n \/\/ a value id.\n for (auto &CallEdge : FS->calls())\n if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())\n assignValueId(CallEdge.first.getGUID());\n }\n\nprotected:\n void writePerModuleGlobalValueSummary();\n\nprivate:\n void writePerModuleFunctionSummaryRecord(SmallVector &NameVals,\n GlobalValueSummary *Summary,\n unsigned ValueID,\n unsigned FSCallsAbbrev,\n unsigned FSCallsProfileAbbrev,\n const Function &F);\n void writeModuleLevelReferences(const GlobalVariable &V,\n SmallVector &NameVals,\n unsigned FSModRefsAbbrev,\n unsigned FSModVTableRefsAbbrev);\n\n void assignValueId(GlobalValue::GUID ValGUID) {\n GUIDToValueIdMap[ValGUID] = ++GlobalValueId;\n }\n\n unsigned getValueId(GlobalValue::GUID ValGUID) {\n const auto &VMI = GUIDToValueIdMap.find(ValGUID);\n \/\/ Expect that any GUID value had a value Id assigned by an\n \/\/ earlier call to assignValueId.\n assert(VMI != GUIDToValueIdMap.end() &&\n \"GUID does not have assigned value Id\");\n return VMI->second;\n }\n\n \/\/ Helper to get the valueId for the type of value recorded in VI.\n unsigned getValueId(ValueInfo VI) {\n if (!VI.haveGVs() || !VI.getValue())\n return getValueId(VI.getGUID());\n return VE.getValueID(VI.getValue());\n }\n\n std::map &valueIds() { return GUIDToValueIdMap; }\n};\n\n\/\/\/ Class to manage the bitcode writing for a module.\nclass ModuleBitcodeWriter : public ModuleBitcodeWriterBase {\n \/\/\/ Pointer to the buffer allocated by caller for bitcode writing.\n const SmallVectorImpl &Buffer;\n\n \/\/\/ True if a module hash record should be written.\n bool GenerateHash;\n\n \/\/\/ If non-null, when GenerateHash is true, the resulting hash is written\n \/\/\/ into ModHash.\n ModuleHash *ModHash;\n\n SHA1 Hasher;\n\n \/\/\/ The start bit of the identification block.\n uint64_t BitcodeStartBit;\n\npublic:\n \/\/\/ Constructs a ModuleBitcodeWriter object for the given Module,\n \/\/\/ writing to the provided \\p Buffer.\n ModuleBitcodeWriter(const Module &M, SmallVectorImpl &Buffer,\n StringTableBuilder &StrtabBuilder,\n BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,\n const ModuleSummaryIndex *Index, bool GenerateHash,\n ModuleHash *ModHash = nullptr)\n : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,\n ShouldPreserveUseListOrder, Index),\n Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),\n BitcodeStartBit(Stream.GetCurrentBitNo()) {}\n\n \/\/\/ Emit the current module to the bitstream.\n void write();\n\nprivate:\n uint64_t bitcodeStartBit() { return BitcodeStartBit; }\n\n size_t addToStrtab(StringRef Str);\n\n void writeAttributeGroupTable();\n void writeAttributeTable();\n void writeTypeTable();\n void writeComdats();\n void writeValueSymbolTableForwardDecl();\n void writeModuleInfo();\n void writeValueAsMetadata(const ValueAsMetadata *MD,\n SmallVectorImpl &Record);\n void writeMDTuple(const MDTuple *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n unsigned createDILocationAbbrev();\n void writeDILocation(const DILocation *N, SmallVectorImpl &Record,\n unsigned &Abbrev);\n unsigned createGenericDINodeAbbrev();\n void writeGenericDINode(const GenericDINode *N,\n SmallVectorImpl &Record, unsigned &Abbrev);\n void writeDISubrange(const DISubrange *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIGenericSubrange(const DIGenericSubrange *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIEnumerator(const DIEnumerator *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDIBasicType(const DIBasicType *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIStringType(const DIStringType *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDIDerivedType(const DIDerivedType *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDICompositeType(const DICompositeType *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDISubroutineType(const DISubroutineType *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIFile(const DIFile *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDICompileUnit(const DICompileUnit *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDISubprogram(const DISubprogram *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDILexicalBlock(const DILexicalBlock *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDILexicalBlockFile(const DILexicalBlockFile *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDICommonBlock(const DICommonBlock *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDINamespace(const DINamespace *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIMacro(const DIMacro *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIArgList(const DIArgList *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIModule(const DIModule *N, SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDITemplateValueParameter(const DITemplateValueParameter *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIGlobalVariable(const DIGlobalVariable *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDILocalVariable(const DILocalVariable *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDILabel(const DILabel *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDIExpression(const DIExpression *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n void writeDIObjCProperty(const DIObjCProperty *N,\n SmallVectorImpl &Record, unsigned Abbrev);\n void writeDIImportedEntity(const DIImportedEntity *N,\n SmallVectorImpl &Record,\n unsigned Abbrev);\n unsigned createNamedMetadataAbbrev();\n void writeNamedMetadata(SmallVectorImpl &Record);\n unsigned createMetadataStringsAbbrev();\n void writeMetadataStrings(ArrayRef Strings,\n SmallVectorImpl &Record);\n void writeMetadataRecords(ArrayRef MDs,\n SmallVectorImpl &Record,\n std::vector *MDAbbrevs = nullptr,\n std::vector *IndexPos = nullptr);\n void writeModuleMetadata();\n void writeFunctionMetadata(const Function &F);\n void writeFunctionMetadataAttachment(const Function &F);\n void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);\n void pushGlobalMetadataAttachment(SmallVectorImpl &Record,\n const GlobalObject &GO);\n void writeModuleMetadataKinds();\n void writeOperandBundleTags();\n void writeSyncScopeNames();\n void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);\n void writeModuleConstants();\n bool pushValueAndType(const Value *V, unsigned InstID,\n SmallVectorImpl &Vals);\n void writeOperandBundles(const CallBase &CB, unsigned InstID);\n void pushValue(const Value *V, unsigned InstID,\n SmallVectorImpl &Vals);\n void pushValueSigned(const Value *V, unsigned InstID,\n SmallVectorImpl &Vals);\n void writeInstruction(const Instruction &I, unsigned InstID,\n SmallVectorImpl &Vals);\n void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);\n void writeGlobalValueSymbolTable(\n DenseMap &FunctionToBitcodeIndex);\n void writeUseList(UseListOrder &&Order);\n void writeUseListBlock(const Function *F);\n void\n writeFunction(const Function &F,\n DenseMap &FunctionToBitcodeIndex);\n void writeBlockInfo();\n void writeModuleHash(size_t BlockStartPos);\n\n unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {\n return unsigned(SSID);\n }\n\n unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }\n};\n\n\/\/\/ Class to manage the bitcode writing for a combined index.\nclass IndexBitcodeWriter : public BitcodeWriterBase {\n \/\/\/ The combined index to write to bitcode.\n const ModuleSummaryIndex &Index;\n\n \/\/\/ When writing a subset of the index for distributed backends, client\n \/\/\/ provides a map of modules to the corresponding GUIDs\/summaries to write.\n const std::map *ModuleToSummariesForIndex;\n\n \/\/\/ Map that holds the correspondence between the GUID used in the combined\n \/\/\/ index and a value id generated by this class to use in references.\n std::map GUIDToValueIdMap;\n\n \/\/\/ Tracks the last value id recorded in the GUIDToValueMap.\n unsigned GlobalValueId = 0;\n\npublic:\n \/\/\/ Constructs a IndexBitcodeWriter object for the given combined index,\n \/\/\/ writing to the provided \\p Buffer. When writing a subset of the index\n \/\/\/ for a distributed backend, provide a \\p ModuleToSummariesForIndex map.\n IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,\n const ModuleSummaryIndex &Index,\n const std::map\n *ModuleToSummariesForIndex = nullptr)\n : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),\n ModuleToSummariesForIndex(ModuleToSummariesForIndex) {\n \/\/ Assign unique value ids to all summaries to be written, for use\n \/\/ in writing out the call graph edges. Save the mapping from GUID\n \/\/ to the new global value id to use when writing those edges, which\n \/\/ are currently saved in the index in terms of GUID.\n forEachSummary([&](GVInfo I, bool) {\n GUIDToValueIdMap[I.first] = ++GlobalValueId;\n });\n }\n\n \/\/\/ The below iterator returns the GUID and associated summary.\n using GVInfo = std::pair;\n\n \/\/\/ Calls the callback for each value GUID and summary to be written to\n \/\/\/ bitcode. This hides the details of whether they are being pulled from the\n \/\/\/ entire index or just those in a provided ModuleToSummariesForIndex map.\n template\n void forEachSummary(Functor Callback) {\n if (ModuleToSummariesForIndex) {\n for (auto &M : *ModuleToSummariesForIndex)\n for (auto &Summary : M.second) {\n Callback(Summary, false);\n \/\/ Ensure aliasee is handled, e.g. for assigning a valueId,\n \/\/ even if we are not importing the aliasee directly (the\n \/\/ imported alias will contain a copy of aliasee).\n if (auto *AS = dyn_cast(Summary.getSecond()))\n Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);\n }\n } else {\n for (auto &Summaries : Index)\n for (auto &Summary : Summaries.second.SummaryList)\n Callback({Summaries.first, Summary.get()}, false);\n }\n }\n\n \/\/\/ Calls the callback for each entry in the modulePaths StringMap that\n \/\/\/ should be written to the module path string table. This hides the details\n \/\/\/ of whether they are being pulled from the entire index or just those in a\n \/\/\/ provided ModuleToSummariesForIndex map.\n template void forEachModule(Functor Callback) {\n if (ModuleToSummariesForIndex) {\n for (const auto &M : *ModuleToSummariesForIndex) {\n const auto &MPI = Index.modulePaths().find(M.first);\n if (MPI == Index.modulePaths().end()) {\n \/\/ This should only happen if the bitcode file was empty, in which\n \/\/ case we shouldn't be importing (the ModuleToSummariesForIndex\n \/\/ would only include the module we are writing and index for).\n assert(ModuleToSummariesForIndex->size() == 1);\n continue;\n }\n Callback(*MPI);\n }\n } else {\n for (const auto &MPSE : Index.modulePaths())\n Callback(MPSE);\n }\n }\n\n \/\/\/ Main entry point for writing a combined index to bitcode.\n void write();\n\nprivate:\n void writeModStrings();\n void writeCombinedGlobalValueSummary();\n\n Optional getValueId(GlobalValue::GUID ValGUID) {\n auto VMI = GUIDToValueIdMap.find(ValGUID);\n if (VMI == GUIDToValueIdMap.end())\n return None;\n return VMI->second;\n }\n\n std::map &valueIds() { return GUIDToValueIdMap; }\n};\n\n} \/\/ end anonymous namespace\n\nstatic unsigned getEncodedCastOpcode(unsigned Opcode) {\n switch (Opcode) {\n default: llvm_unreachable(\"Unknown cast instruction!\");\n case Instruction::Trunc : return bitc::CAST_TRUNC;\n case Instruction::ZExt : return bitc::CAST_ZEXT;\n case Instruction::SExt : return bitc::CAST_SEXT;\n case Instruction::FPToUI : return bitc::CAST_FPTOUI;\n case Instruction::FPToSI : return bitc::CAST_FPTOSI;\n case Instruction::UIToFP : return bitc::CAST_UITOFP;\n case Instruction::SIToFP : return bitc::CAST_SITOFP;\n case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;\n case Instruction::FPExt : return bitc::CAST_FPEXT;\n case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;\n case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;\n case Instruction::BitCast : return bitc::CAST_BITCAST;\n case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;\n }\n}\n\nstatic unsigned getEncodedUnaryOpcode(unsigned Opcode) {\n switch (Opcode) {\n default: llvm_unreachable(\"Unknown binary instruction!\");\n case Instruction::FNeg: return bitc::UNOP_FNEG;\n }\n}\n\nstatic unsigned getEncodedBinaryOpcode(unsigned Opcode) {\n switch (Opcode) {\n default: llvm_unreachable(\"Unknown binary instruction!\");\n case Instruction::Add:\n case Instruction::FAdd: return bitc::BINOP_ADD;\n case Instruction::Sub:\n case Instruction::FSub: return bitc::BINOP_SUB;\n case Instruction::Mul:\n case Instruction::FMul: return bitc::BINOP_MUL;\n case Instruction::UDiv: return bitc::BINOP_UDIV;\n case Instruction::FDiv:\n case Instruction::SDiv: return bitc::BINOP_SDIV;\n case Instruction::URem: return bitc::BINOP_UREM;\n case Instruction::FRem:\n case Instruction::SRem: return bitc::BINOP_SREM;\n case Instruction::Shl: return bitc::BINOP_SHL;\n case Instruction::LShr: return bitc::BINOP_LSHR;\n case Instruction::AShr: return bitc::BINOP_ASHR;\n case Instruction::And: return bitc::BINOP_AND;\n case Instruction::Or: return bitc::BINOP_OR;\n case Instruction::Xor: return bitc::BINOP_XOR;\n }\n}\n\nstatic unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {\n switch (Op) {\n default: llvm_unreachable(\"Unknown RMW operation!\");\n case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;\n case AtomicRMWInst::Add: return bitc::RMW_ADD;\n case AtomicRMWInst::Sub: return bitc::RMW_SUB;\n case AtomicRMWInst::And: return bitc::RMW_AND;\n case AtomicRMWInst::Nand: return bitc::RMW_NAND;\n case AtomicRMWInst::Or: return bitc::RMW_OR;\n case AtomicRMWInst::Xor: return bitc::RMW_XOR;\n case AtomicRMWInst::Max: return bitc::RMW_MAX;\n case AtomicRMWInst::Min: return bitc::RMW_MIN;\n case AtomicRMWInst::UMax: return bitc::RMW_UMAX;\n case AtomicRMWInst::UMin: return bitc::RMW_UMIN;\n case AtomicRMWInst::FAdd: return bitc::RMW_FADD;\n case AtomicRMWInst::FSub: return bitc::RMW_FSUB;\n }\n}\n\nstatic unsigned getEncodedOrdering(AtomicOrdering Ordering) {\n switch (Ordering) {\n case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;\n case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;\n case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;\n case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;\n case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;\n case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;\n case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;\n }\n llvm_unreachable(\"Invalid ordering\");\n}\n\nstatic void writeStringRecord(BitstreamWriter &Stream, unsigned Code,\n StringRef Str, unsigned AbbrevToUse) {\n SmallVector Vals;\n\n \/\/ Code: [strchar x N]\n for (unsigned i = 0, e = Str.size(); i != e; ++i) {\n if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))\n AbbrevToUse = 0;\n Vals.push_back(Str[i]);\n }\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(Code, Vals, AbbrevToUse);\n}\n\nstatic uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {\n switch (Kind) {\n case Attribute::Alignment:\n return bitc::ATTR_KIND_ALIGNMENT;\n case Attribute::AllocSize:\n return bitc::ATTR_KIND_ALLOC_SIZE;\n case Attribute::AlwaysInline:\n return bitc::ATTR_KIND_ALWAYS_INLINE;\n case Attribute::ArgMemOnly:\n return bitc::ATTR_KIND_ARGMEMONLY;\n case Attribute::Builtin:\n return bitc::ATTR_KIND_BUILTIN;\n case Attribute::ByVal:\n return bitc::ATTR_KIND_BY_VAL;\n case Attribute::Convergent:\n return bitc::ATTR_KIND_CONVERGENT;\n case Attribute::InAlloca:\n return bitc::ATTR_KIND_IN_ALLOCA;\n case Attribute::Cold:\n return bitc::ATTR_KIND_COLD;\n case Attribute::Hot:\n return bitc::ATTR_KIND_HOT;\n case Attribute::InaccessibleMemOnly:\n return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;\n case Attribute::InaccessibleMemOrArgMemOnly:\n return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;\n case Attribute::InlineHint:\n return bitc::ATTR_KIND_INLINE_HINT;\n case Attribute::InReg:\n return bitc::ATTR_KIND_IN_REG;\n case Attribute::JumpTable:\n return bitc::ATTR_KIND_JUMP_TABLE;\n case Attribute::MinSize:\n return bitc::ATTR_KIND_MIN_SIZE;\n case Attribute::Naked:\n return bitc::ATTR_KIND_NAKED;\n case Attribute::Nest:\n return bitc::ATTR_KIND_NEST;\n case Attribute::NoAlias:\n return bitc::ATTR_KIND_NO_ALIAS;\n case Attribute::NoBuiltin:\n return bitc::ATTR_KIND_NO_BUILTIN;\n case Attribute::NoCallback:\n return bitc::ATTR_KIND_NO_CALLBACK;\n case Attribute::NoCapture:\n return bitc::ATTR_KIND_NO_CAPTURE;\n case Attribute::NoDuplicate:\n return bitc::ATTR_KIND_NO_DUPLICATE;\n case Attribute::NoFree:\n return bitc::ATTR_KIND_NOFREE;\n case Attribute::NoImplicitFloat:\n return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;\n case Attribute::NoInline:\n return bitc::ATTR_KIND_NO_INLINE;\n case Attribute::NoRecurse:\n return bitc::ATTR_KIND_NO_RECURSE;\n case Attribute::NoMerge:\n return bitc::ATTR_KIND_NO_MERGE;\n case Attribute::NonLazyBind:\n return bitc::ATTR_KIND_NON_LAZY_BIND;\n case Attribute::NonNull:\n return bitc::ATTR_KIND_NON_NULL;\n case Attribute::Dereferenceable:\n return bitc::ATTR_KIND_DEREFERENCEABLE;\n case Attribute::DereferenceableOrNull:\n return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;\n case Attribute::NoRedZone:\n return bitc::ATTR_KIND_NO_RED_ZONE;\n case Attribute::NoReturn:\n return bitc::ATTR_KIND_NO_RETURN;\n case Attribute::NoSync:\n return bitc::ATTR_KIND_NOSYNC;\n case Attribute::NoCfCheck:\n return bitc::ATTR_KIND_NOCF_CHECK;\n case Attribute::NoProfile:\n return bitc::ATTR_KIND_NO_PROFILE;\n case Attribute::NoUnwind:\n return bitc::ATTR_KIND_NO_UNWIND;\n case Attribute::NullPointerIsValid:\n return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;\n case Attribute::OptForFuzzing:\n return bitc::ATTR_KIND_OPT_FOR_FUZZING;\n case Attribute::OptimizeForSize:\n return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;\n case Attribute::OptimizeNone:\n return bitc::ATTR_KIND_OPTIMIZE_NONE;\n case Attribute::ReadNone:\n return bitc::ATTR_KIND_READ_NONE;\n case Attribute::ReadOnly:\n return bitc::ATTR_KIND_READ_ONLY;\n case Attribute::Returned:\n return bitc::ATTR_KIND_RETURNED;\n case Attribute::ReturnsTwice:\n return bitc::ATTR_KIND_RETURNS_TWICE;\n case Attribute::SExt:\n return bitc::ATTR_KIND_S_EXT;\n case Attribute::Speculatable:\n return bitc::ATTR_KIND_SPECULATABLE;\n case Attribute::StackAlignment:\n return bitc::ATTR_KIND_STACK_ALIGNMENT;\n case Attribute::StackProtect:\n return bitc::ATTR_KIND_STACK_PROTECT;\n case Attribute::StackProtectReq:\n return bitc::ATTR_KIND_STACK_PROTECT_REQ;\n case Attribute::StackProtectStrong:\n return bitc::ATTR_KIND_STACK_PROTECT_STRONG;\n case Attribute::SafeStack:\n return bitc::ATTR_KIND_SAFESTACK;\n case Attribute::ShadowCallStack:\n return bitc::ATTR_KIND_SHADOWCALLSTACK;\n case Attribute::StrictFP:\n return bitc::ATTR_KIND_STRICT_FP;\n case Attribute::StructRet:\n return bitc::ATTR_KIND_STRUCT_RET;\n case Attribute::SanitizeAddress:\n return bitc::ATTR_KIND_SANITIZE_ADDRESS;\n case Attribute::SanitizeHWAddress:\n return bitc::ATTR_KIND_SANITIZE_HWADDRESS;\n case Attribute::SanitizeThread:\n return bitc::ATTR_KIND_SANITIZE_THREAD;\n case Attribute::SanitizeMemory:\n return bitc::ATTR_KIND_SANITIZE_MEMORY;\n case Attribute::SpeculativeLoadHardening:\n return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;\n case Attribute::SwiftError:\n return bitc::ATTR_KIND_SWIFT_ERROR;\n case Attribute::SwiftSelf:\n return bitc::ATTR_KIND_SWIFT_SELF;\n case Attribute::UWTable:\n return bitc::ATTR_KIND_UW_TABLE;\n case Attribute::VScaleRange:\n return bitc::ATTR_KIND_VSCALE_RANGE;\n case Attribute::WillReturn:\n return bitc::ATTR_KIND_WILLRETURN;\n case Attribute::WriteOnly:\n return bitc::ATTR_KIND_WRITEONLY;\n case Attribute::ZExt:\n return bitc::ATTR_KIND_Z_EXT;\n case Attribute::ImmArg:\n return bitc::ATTR_KIND_IMMARG;\n case Attribute::SanitizeMemTag:\n return bitc::ATTR_KIND_SANITIZE_MEMTAG;\n case Attribute::Preallocated:\n return bitc::ATTR_KIND_PREALLOCATED;\n case Attribute::NoUndef:\n return bitc::ATTR_KIND_NOUNDEF;\n case Attribute::ByRef:\n return bitc::ATTR_KIND_BYREF;\n case Attribute::MustProgress:\n return bitc::ATTR_KIND_MUSTPROGRESS;\n case Attribute::EndAttrKinds:\n llvm_unreachable(\"Can not encode end-attribute kinds marker.\");\n case Attribute::None:\n llvm_unreachable(\"Can not encode none-attribute.\");\n case Attribute::EmptyKey:\n case Attribute::TombstoneKey:\n llvm_unreachable(\"Trying to encode EmptyKey\/TombstoneKey\");\n }\n\n llvm_unreachable(\"Trying to encode unknown attribute\");\n}\n\nvoid ModuleBitcodeWriter::writeAttributeGroupTable() {\n const std::vector &AttrGrps =\n VE.getAttributeGroups();\n if (AttrGrps.empty()) return;\n\n Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);\n\n SmallVector Record;\n for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {\n unsigned AttrListIndex = Pair.first;\n AttributeSet AS = Pair.second;\n Record.push_back(VE.getAttributeGroupID(Pair));\n Record.push_back(AttrListIndex);\n\n for (Attribute Attr : AS) {\n if (Attr.isEnumAttribute()) {\n Record.push_back(0);\n Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));\n } else if (Attr.isIntAttribute()) {\n Record.push_back(1);\n Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));\n Record.push_back(Attr.getValueAsInt());\n } else if (Attr.isStringAttribute()) {\n StringRef Kind = Attr.getKindAsString();\n StringRef Val = Attr.getValueAsString();\n\n Record.push_back(Val.empty() ? 3 : 4);\n Record.append(Kind.begin(), Kind.end());\n Record.push_back(0);\n if (!Val.empty()) {\n Record.append(Val.begin(), Val.end());\n Record.push_back(0);\n }\n } else {\n assert(Attr.isTypeAttribute());\n Type *Ty = Attr.getValueAsType();\n Record.push_back(Ty ? 6 : 5);\n Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));\n if (Ty)\n Record.push_back(VE.getTypeID(Attr.getValueAsType()));\n }\n }\n\n Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);\n Record.clear();\n }\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeAttributeTable() {\n const std::vector &Attrs = VE.getAttributeLists();\n if (Attrs.empty()) return;\n\n Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);\n\n SmallVector Record;\n for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {\n AttributeList AL = Attrs[i];\n for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {\n AttributeSet AS = AL.getAttributes(i);\n if (AS.hasAttributes())\n Record.push_back(VE.getAttributeGroupID({i, AS}));\n }\n\n Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);\n Record.clear();\n }\n\n Stream.ExitBlock();\n}\n\n\/\/\/ WriteTypeTable - Write out the type table for a module.\nvoid ModuleBitcodeWriter::writeTypeTable() {\n const ValueEnumerator::TypeList &TypeList = VE.getTypes();\n\n Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 \/*count from # abbrevs *\/);\n SmallVector TypeVals;\n\n uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();\n\n \/\/ Abbrev for TYPE_CODE_POINTER.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));\n Abbv->Add(BitCodeAbbrevOp(0)); \/\/ Addrspace = 0\n unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for TYPE_CODE_FUNCTION.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); \/\/ isvararg\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));\n unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for TYPE_CODE_STRUCT_ANON.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); \/\/ ispacked\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));\n unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for TYPE_CODE_STRUCT_NAME.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));\n unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for TYPE_CODE_STRUCT_NAMED.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); \/\/ ispacked\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));\n unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for TYPE_CODE_ARRAY.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ size\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));\n unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Emit an entry count so the reader can reserve space.\n TypeVals.push_back(TypeList.size());\n Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);\n TypeVals.clear();\n\n \/\/ Loop over all of the types, emitting each in turn.\n for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {\n Type *T = TypeList[i];\n int AbbrevToUse = 0;\n unsigned Code = 0;\n\n switch (T->getTypeID()) {\n case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;\n case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;\n case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;\n case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;\n case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;\n case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;\n case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;\n case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;\n case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;\n case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;\n case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;\n case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;\n case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;\n case Type::IntegerTyID:\n \/\/ INTEGER: [width]\n Code = bitc::TYPE_CODE_INTEGER;\n TypeVals.push_back(cast(T)->getBitWidth());\n break;\n case Type::PointerTyID: {\n PointerType *PTy = cast(T);\n \/\/ POINTER: [pointee type, address space]\n Code = bitc::TYPE_CODE_POINTER;\n TypeVals.push_back(VE.getTypeID(PTy->getElementType()));\n unsigned AddressSpace = PTy->getAddressSpace();\n TypeVals.push_back(AddressSpace);\n if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;\n break;\n }\n case Type::FunctionTyID: {\n FunctionType *FT = cast(T);\n \/\/ FUNCTION: [isvararg, retty, paramty x N]\n Code = bitc::TYPE_CODE_FUNCTION;\n TypeVals.push_back(FT->isVarArg());\n TypeVals.push_back(VE.getTypeID(FT->getReturnType()));\n for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)\n TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));\n AbbrevToUse = FunctionAbbrev;\n break;\n }\n case Type::StructTyID: {\n StructType *ST = cast(T);\n \/\/ STRUCT: [ispacked, eltty x N]\n TypeVals.push_back(ST->isPacked());\n \/\/ Output all of the element types.\n for (StructType::element_iterator I = ST->element_begin(),\n E = ST->element_end(); I != E; ++I)\n TypeVals.push_back(VE.getTypeID(*I));\n\n if (ST->isLiteral()) {\n Code = bitc::TYPE_CODE_STRUCT_ANON;\n AbbrevToUse = StructAnonAbbrev;\n } else {\n if (ST->isOpaque()) {\n Code = bitc::TYPE_CODE_OPAQUE;\n } else {\n Code = bitc::TYPE_CODE_STRUCT_NAMED;\n AbbrevToUse = StructNamedAbbrev;\n }\n\n \/\/ Emit the name if it is present.\n if (!ST->getName().empty())\n writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),\n StructNameAbbrev);\n }\n break;\n }\n case Type::ArrayTyID: {\n ArrayType *AT = cast(T);\n \/\/ ARRAY: [numelts, eltty]\n Code = bitc::TYPE_CODE_ARRAY;\n TypeVals.push_back(AT->getNumElements());\n TypeVals.push_back(VE.getTypeID(AT->getElementType()));\n AbbrevToUse = ArrayAbbrev;\n break;\n }\n case Type::FixedVectorTyID:\n case Type::ScalableVectorTyID: {\n VectorType *VT = cast(T);\n \/\/ VECTOR [numelts, eltty] or\n \/\/ [numelts, eltty, scalable]\n Code = bitc::TYPE_CODE_VECTOR;\n TypeVals.push_back(VT->getElementCount().getKnownMinValue());\n TypeVals.push_back(VE.getTypeID(VT->getElementType()));\n if (isa(VT))\n TypeVals.push_back(true);\n break;\n }\n }\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(Code, TypeVals, AbbrevToUse);\n TypeVals.clear();\n }\n\n Stream.ExitBlock();\n}\n\nstatic unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {\n switch (Linkage) {\n case GlobalValue::ExternalLinkage:\n return 0;\n case GlobalValue::WeakAnyLinkage:\n return 16;\n case GlobalValue::AppendingLinkage:\n return 2;\n case GlobalValue::InternalLinkage:\n return 3;\n case GlobalValue::LinkOnceAnyLinkage:\n return 18;\n case GlobalValue::ExternalWeakLinkage:\n return 7;\n case GlobalValue::CommonLinkage:\n return 8;\n case GlobalValue::PrivateLinkage:\n return 9;\n case GlobalValue::WeakODRLinkage:\n return 17;\n case GlobalValue::LinkOnceODRLinkage:\n return 19;\n case GlobalValue::AvailableExternallyLinkage:\n return 12;\n }\n llvm_unreachable(\"Invalid linkage\");\n}\n\nstatic unsigned getEncodedLinkage(const GlobalValue &GV) {\n return getEncodedLinkage(GV.getLinkage());\n}\n\nstatic uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {\n uint64_t RawFlags = 0;\n RawFlags |= Flags.ReadNone;\n RawFlags |= (Flags.ReadOnly << 1);\n RawFlags |= (Flags.NoRecurse << 2);\n RawFlags |= (Flags.ReturnDoesNotAlias << 3);\n RawFlags |= (Flags.NoInline << 4);\n RawFlags |= (Flags.AlwaysInline << 5);\n return RawFlags;\n}\n\n\/\/ Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags\n\/\/ in BitcodeReader.cpp.\nstatic uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {\n uint64_t RawFlags = 0;\n\n RawFlags |= Flags.NotEligibleToImport; \/\/ bool\n RawFlags |= (Flags.Live << 1);\n RawFlags |= (Flags.DSOLocal << 2);\n RawFlags |= (Flags.CanAutoHide << 3);\n\n \/\/ Linkage don't need to be remapped at that time for the summary. Any future\n \/\/ change to the getEncodedLinkage() function will need to be taken into\n \/\/ account here as well.\n RawFlags = (RawFlags << 4) | Flags.Linkage; \/\/ 4 bits\n\n RawFlags |= (Flags.Visibility << 8); \/\/ 2 bits\n\n return RawFlags;\n}\n\nstatic uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {\n uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |\n (Flags.Constant << 2) | Flags.VCallVisibility << 3;\n return RawFlags;\n}\n\nstatic unsigned getEncodedVisibility(const GlobalValue &GV) {\n switch (GV.getVisibility()) {\n case GlobalValue::DefaultVisibility: return 0;\n case GlobalValue::HiddenVisibility: return 1;\n case GlobalValue::ProtectedVisibility: return 2;\n }\n llvm_unreachable(\"Invalid visibility\");\n}\n\nstatic unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {\n switch (GV.getDLLStorageClass()) {\n case GlobalValue::DefaultStorageClass: return 0;\n case GlobalValue::DLLImportStorageClass: return 1;\n case GlobalValue::DLLExportStorageClass: return 2;\n }\n llvm_unreachable(\"Invalid DLL storage class\");\n}\n\nstatic unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {\n switch (GV.getThreadLocalMode()) {\n case GlobalVariable::NotThreadLocal: return 0;\n case GlobalVariable::GeneralDynamicTLSModel: return 1;\n case GlobalVariable::LocalDynamicTLSModel: return 2;\n case GlobalVariable::InitialExecTLSModel: return 3;\n case GlobalVariable::LocalExecTLSModel: return 4;\n }\n llvm_unreachable(\"Invalid TLS model\");\n}\n\nstatic unsigned getEncodedComdatSelectionKind(const Comdat &C) {\n switch (C.getSelectionKind()) {\n case Comdat::Any:\n return bitc::COMDAT_SELECTION_KIND_ANY;\n case Comdat::ExactMatch:\n return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;\n case Comdat::Largest:\n return bitc::COMDAT_SELECTION_KIND_LARGEST;\n case Comdat::NoDuplicates:\n return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;\n case Comdat::SameSize:\n return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;\n }\n llvm_unreachable(\"Invalid selection kind\");\n}\n\nstatic unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {\n switch (GV.getUnnamedAddr()) {\n case GlobalValue::UnnamedAddr::None: return 0;\n case GlobalValue::UnnamedAddr::Local: return 2;\n case GlobalValue::UnnamedAddr::Global: return 1;\n }\n llvm_unreachable(\"Invalid unnamed_addr\");\n}\n\nsize_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {\n if (GenerateHash)\n Hasher.update(Str);\n return StrtabBuilder.add(Str);\n}\n\nvoid ModuleBitcodeWriter::writeComdats() {\n SmallVector Vals;\n for (const Comdat *C : VE.getComdats()) {\n \/\/ COMDAT: [strtab offset, strtab size, selection_kind]\n Vals.push_back(addToStrtab(C->getName()));\n Vals.push_back(C->getName().size());\n Vals.push_back(getEncodedComdatSelectionKind(*C));\n Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, \/*AbbrevToUse=*\/0);\n Vals.clear();\n }\n}\n\n\/\/\/ Write a record that will eventually hold the word offset of the\n\/\/\/ module-level VST. For now the offset is 0, which will be backpatched\n\/\/\/ after the real VST is written. Saves the bit offset to backpatch.\nvoid ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {\n \/\/ Write a placeholder value in for the offset of the real VST,\n \/\/ which is written after the function blocks so that it can include\n \/\/ the offset of each function. The placeholder offset will be\n \/\/ updated when the real VST is written.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));\n \/\/ Blocks are 32-bit aligned, so we can use a 32-bit word offset to\n \/\/ hold the real VST offset. Must use fixed instead of VBR as we don't\n \/\/ know how many VBR chunks to reserve ahead of time.\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Emit the placeholder\n uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};\n Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);\n\n \/\/ Compute and save the bit offset to the placeholder, which will be\n \/\/ patched when the real VST is written. We can simply subtract the 32-bit\n \/\/ fixed size from the current bit number to get the location to backpatch.\n VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;\n}\n\nenum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };\n\n\/\/\/ Determine the encoding to use for the given string name and length.\nstatic StringEncoding getStringEncoding(StringRef Str) {\n bool isChar6 = true;\n for (char C : Str) {\n if (isChar6)\n isChar6 = BitCodeAbbrevOp::isChar6(C);\n if ((unsigned char)C & 128)\n \/\/ don't bother scanning the rest.\n return SE_Fixed8;\n }\n if (isChar6)\n return SE_Char6;\n return SE_Fixed7;\n}\n\n\/\/\/ Emit top-level description of module, including target triple, inline asm,\n\/\/\/ descriptors for global variables, and function prototype info.\n\/\/\/ Returns the bit offset to backpatch with the location of the real VST.\nvoid ModuleBitcodeWriter::writeModuleInfo() {\n \/\/ Emit various pieces of data attached to a module.\n if (!M.getTargetTriple().empty())\n writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),\n 0 \/*TODO*\/);\n const std::string &DL = M.getDataLayoutStr();\n if (!DL.empty())\n writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 \/*TODO*\/);\n if (!M.getModuleInlineAsm().empty())\n writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),\n 0 \/*TODO*\/);\n\n \/\/ Emit information about sections and GC, computing how many there are. Also\n \/\/ compute the maximum alignment value.\n std::map SectionMap;\n std::map GCMap;\n MaybeAlign MaxAlignment;\n unsigned MaxGlobalType = 0;\n const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {\n if (A)\n MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);\n };\n for (const GlobalVariable &GV : M.globals()) {\n UpdateMaxAlignment(GV.getAlign());\n MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));\n if (GV.hasSection()) {\n \/\/ Give section names unique ID's.\n unsigned &Entry = SectionMap[std::string(GV.getSection())];\n if (!Entry) {\n writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),\n 0 \/*TODO*\/);\n Entry = SectionMap.size();\n }\n }\n }\n for (const Function &F : M) {\n UpdateMaxAlignment(F.getAlign());\n if (F.hasSection()) {\n \/\/ Give section names unique ID's.\n unsigned &Entry = SectionMap[std::string(F.getSection())];\n if (!Entry) {\n writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),\n 0 \/*TODO*\/);\n Entry = SectionMap.size();\n }\n }\n if (F.hasGC()) {\n \/\/ Same for GC names.\n unsigned &Entry = GCMap[F.getGC()];\n if (!Entry) {\n writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),\n 0 \/*TODO*\/);\n Entry = GCMap.size();\n }\n }\n }\n\n \/\/ Emit abbrev for globals, now that we know # sections and max alignment.\n unsigned SimpleGVarAbbrev = 0;\n if (!M.global_empty()) {\n \/\/ Add an abbrev for common globals with no visibility or thread localness.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,\n Log2_32_Ceil(MaxGlobalType+1)));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ AddrSpace << 2\n \/\/| explicitType << 1\n \/\/| constant\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ Initializer.\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); \/\/ Linkage.\n if (!MaxAlignment) \/\/ Alignment.\n Abbv->Add(BitCodeAbbrevOp(0));\n else {\n unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,\n Log2_32_Ceil(MaxEncAlignment+1)));\n }\n if (SectionMap.empty()) \/\/ Section.\n Abbv->Add(BitCodeAbbrevOp(0));\n else\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,\n Log2_32_Ceil(SectionMap.size()+1)));\n \/\/ Don't bother emitting vis + thread local.\n SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n }\n\n SmallVector Vals;\n \/\/ Emit the module's source file name.\n {\n StringEncoding Bits = getStringEncoding(M.getSourceFileName());\n BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);\n if (Bits == SE_Char6)\n AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);\n else if (Bits == SE_Fixed7)\n AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);\n\n \/\/ MODULE_CODE_SOURCE_FILENAME: [namechar x N]\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(AbbrevOpToUse);\n unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n for (const auto P : M.getSourceFileName())\n Vals.push_back((unsigned char)P);\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);\n Vals.clear();\n }\n\n \/\/ Emit the global variable information.\n for (const GlobalVariable &GV : M.globals()) {\n unsigned AbbrevToUse = 0;\n\n \/\/ GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,\n \/\/ linkage, alignment, section, visibility, threadlocal,\n \/\/ unnamed_addr, externally_initialized, dllstorageclass,\n \/\/ comdat, attributes, DSO_Local]\n Vals.push_back(addToStrtab(GV.getName()));\n Vals.push_back(GV.getName().size());\n Vals.push_back(VE.getTypeID(GV.getValueType()));\n Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());\n Vals.push_back(GV.isDeclaration() ? 0 :\n (VE.getValueID(GV.getInitializer()) + 1));\n Vals.push_back(getEncodedLinkage(GV));\n Vals.push_back(getEncodedAlign(GV.getAlign()));\n Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]\n : 0);\n if (GV.isThreadLocal() ||\n GV.getVisibility() != GlobalValue::DefaultVisibility ||\n GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||\n GV.isExternallyInitialized() ||\n GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||\n GV.hasComdat() ||\n GV.hasAttributes() ||\n GV.isDSOLocal() ||\n GV.hasPartition()) {\n Vals.push_back(getEncodedVisibility(GV));\n Vals.push_back(getEncodedThreadLocalMode(GV));\n Vals.push_back(getEncodedUnnamedAddr(GV));\n Vals.push_back(GV.isExternallyInitialized());\n Vals.push_back(getEncodedDLLStorageClass(GV));\n Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);\n\n auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);\n Vals.push_back(VE.getAttributeListID(AL));\n\n Vals.push_back(GV.isDSOLocal());\n Vals.push_back(addToStrtab(GV.getPartition()));\n Vals.push_back(GV.getPartition().size());\n } else {\n AbbrevToUse = SimpleGVarAbbrev;\n }\n\n Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);\n Vals.clear();\n }\n\n \/\/ Emit the function proto information.\n for (const Function &F : M) {\n \/\/ FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,\n \/\/ linkage, paramattrs, alignment, section, visibility, gc,\n \/\/ unnamed_addr, prologuedata, dllstorageclass, comdat,\n \/\/ prefixdata, personalityfn, DSO_Local, addrspace]\n Vals.push_back(addToStrtab(F.getName()));\n Vals.push_back(F.getName().size());\n Vals.push_back(VE.getTypeID(F.getFunctionType()));\n Vals.push_back(F.getCallingConv());\n Vals.push_back(F.isDeclaration());\n Vals.push_back(getEncodedLinkage(F));\n Vals.push_back(VE.getAttributeListID(F.getAttributes()));\n Vals.push_back(getEncodedAlign(F.getAlign()));\n Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]\n : 0);\n Vals.push_back(getEncodedVisibility(F));\n Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);\n Vals.push_back(getEncodedUnnamedAddr(F));\n Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)\n : 0);\n Vals.push_back(getEncodedDLLStorageClass(F));\n Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);\n Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)\n : 0);\n Vals.push_back(\n F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);\n\n Vals.push_back(F.isDSOLocal());\n Vals.push_back(F.getAddressSpace());\n Vals.push_back(addToStrtab(F.getPartition()));\n Vals.push_back(F.getPartition().size());\n\n unsigned AbbrevToUse = 0;\n Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);\n Vals.clear();\n }\n\n \/\/ Emit the alias information.\n for (const GlobalAlias &A : M.aliases()) {\n \/\/ ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,\n \/\/ visibility, dllstorageclass, threadlocal, unnamed_addr,\n \/\/ DSO_Local]\n Vals.push_back(addToStrtab(A.getName()));\n Vals.push_back(A.getName().size());\n Vals.push_back(VE.getTypeID(A.getValueType()));\n Vals.push_back(A.getType()->getAddressSpace());\n Vals.push_back(VE.getValueID(A.getAliasee()));\n Vals.push_back(getEncodedLinkage(A));\n Vals.push_back(getEncodedVisibility(A));\n Vals.push_back(getEncodedDLLStorageClass(A));\n Vals.push_back(getEncodedThreadLocalMode(A));\n Vals.push_back(getEncodedUnnamedAddr(A));\n Vals.push_back(A.isDSOLocal());\n Vals.push_back(addToStrtab(A.getPartition()));\n Vals.push_back(A.getPartition().size());\n\n unsigned AbbrevToUse = 0;\n Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);\n Vals.clear();\n }\n\n \/\/ Emit the ifunc information.\n for (const GlobalIFunc &I : M.ifuncs()) {\n \/\/ IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver\n \/\/ val#, linkage, visibility, DSO_Local]\n Vals.push_back(addToStrtab(I.getName()));\n Vals.push_back(I.getName().size());\n Vals.push_back(VE.getTypeID(I.getValueType()));\n Vals.push_back(I.getType()->getAddressSpace());\n Vals.push_back(VE.getValueID(I.getResolver()));\n Vals.push_back(getEncodedLinkage(I));\n Vals.push_back(getEncodedVisibility(I));\n Vals.push_back(I.isDSOLocal());\n Vals.push_back(addToStrtab(I.getPartition()));\n Vals.push_back(I.getPartition().size());\n Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);\n Vals.clear();\n }\n\n writeValueSymbolTableForwardDecl();\n}\n\nstatic uint64_t getOptimizationFlags(const Value *V) {\n uint64_t Flags = 0;\n\n if (const auto *OBO = dyn_cast(V)) {\n if (OBO->hasNoSignedWrap())\n Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;\n if (OBO->hasNoUnsignedWrap())\n Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;\n } else if (const auto *PEO = dyn_cast(V)) {\n if (PEO->isExact())\n Flags |= 1 << bitc::PEO_EXACT;\n } else if (const auto *FPMO = dyn_cast(V)) {\n if (FPMO->hasAllowReassoc())\n Flags |= bitc::AllowReassoc;\n if (FPMO->hasNoNaNs())\n Flags |= bitc::NoNaNs;\n if (FPMO->hasNoInfs())\n Flags |= bitc::NoInfs;\n if (FPMO->hasNoSignedZeros())\n Flags |= bitc::NoSignedZeros;\n if (FPMO->hasAllowReciprocal())\n Flags |= bitc::AllowReciprocal;\n if (FPMO->hasAllowContract())\n Flags |= bitc::AllowContract;\n if (FPMO->hasApproxFunc())\n Flags |= bitc::ApproxFunc;\n }\n\n return Flags;\n}\n\nvoid ModuleBitcodeWriter::writeValueAsMetadata(\n const ValueAsMetadata *MD, SmallVectorImpl &Record) {\n \/\/ Mimic an MDNode with a value as one operand.\n Value *V = MD->getValue();\n Record.push_back(VE.getTypeID(V->getType()));\n Record.push_back(VE.getValueID(V));\n Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {\n Metadata *MD = N->getOperand(i);\n assert(!(MD && isa(MD)) &&\n \"Unexpected function-local metadata\");\n Record.push_back(VE.getMetadataOrNullID(MD));\n }\n Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE\n : bitc::METADATA_NODE,\n Record, Abbrev);\n Record.clear();\n}\n\nunsigned ModuleBitcodeWriter::createDILocationAbbrev() {\n \/\/ Assume the column is usually under 128, and always output the inlined-at\n \/\/ location (it's never more expensive than building an array size 1).\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));\n return Stream.EmitAbbrev(std::move(Abbv));\n}\n\nvoid ModuleBitcodeWriter::writeDILocation(const DILocation *N,\n SmallVectorImpl &Record,\n unsigned &Abbrev) {\n if (!Abbrev)\n Abbrev = createDILocationAbbrev();\n\n Record.push_back(N->isDistinct());\n Record.push_back(N->getLine());\n Record.push_back(N->getColumn());\n Record.push_back(VE.getMetadataID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));\n Record.push_back(N->isImplicitCode());\n\n Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);\n Record.clear();\n}\n\nunsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {\n \/\/ Assume the column is usually under 128, and always output the inlined-at\n \/\/ location (it's never more expensive than building an array size 1).\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n return Stream.EmitAbbrev(std::move(Abbv));\n}\n\nvoid ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,\n SmallVectorImpl &Record,\n unsigned &Abbrev) {\n if (!Abbrev)\n Abbrev = createGenericDINodeAbbrev();\n\n Record.push_back(N->isDistinct());\n Record.push_back(N->getTag());\n Record.push_back(0); \/\/ Per-tag version field; unused for now.\n\n for (auto &I : N->operands())\n Record.push_back(VE.getMetadataOrNullID(I));\n\n Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n const uint64_t Version = 2 << 1;\n Record.push_back((uint64_t)N->isDistinct() | Version);\n Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));\n\n Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIGenericSubrange(\n const DIGenericSubrange *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back((uint64_t)N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));\n\n Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);\n Record.clear();\n}\n\nstatic void emitSignedInt64(SmallVectorImpl &Vals, uint64_t V) {\n if ((int64_t)V >= 0)\n Vals.push_back(V << 1);\n else\n Vals.push_back((-V << 1) | 1);\n}\n\nstatic void emitWideAPInt(SmallVectorImpl &Vals, const APInt &A) {\n \/\/ We have an arbitrary precision integer value to write whose\n \/\/ bit width is > 64. However, in canonical unsigned integer\n \/\/ format it is likely that the high bits are going to be zero.\n \/\/ So, we only write the number of active words.\n unsigned NumWords = A.getActiveWords();\n const uint64_t *RawData = A.getRawData();\n for (unsigned i = 0; i < NumWords; i++)\n emitSignedInt64(Vals, RawData[i]);\n}\n\nvoid ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n const uint64_t IsBigInt = 1 << 2;\n Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());\n Record.push_back(N->getValue().getBitWidth());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n emitWideAPInt(Record, N->getValue());\n\n Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(N->getTag());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(N->getSizeInBits());\n Record.push_back(N->getAlignInBits());\n Record.push_back(N->getEncoding());\n Record.push_back(N->getFlags());\n\n Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(N->getTag());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));\n Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));\n Record.push_back(N->getSizeInBits());\n Record.push_back(N->getAlignInBits());\n Record.push_back(N->getEncoding());\n\n Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(N->getTag());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));\n Record.push_back(N->getSizeInBits());\n Record.push_back(N->getAlignInBits());\n Record.push_back(N->getOffsetInBits());\n Record.push_back(N->getFlags());\n Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));\n\n \/\/ DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means\n \/\/ that there is no DWARF address space associated with DIDerivedType.\n if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())\n Record.push_back(*DWARFAddressSpace + 1);\n else\n Record.push_back(0);\n\n Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDICompositeType(\n const DICompositeType *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n const unsigned IsNotUsedInOldTypeRef = 0x2;\n Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());\n Record.push_back(N->getTag());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));\n Record.push_back(N->getSizeInBits());\n Record.push_back(N->getAlignInBits());\n Record.push_back(N->getOffsetInBits());\n Record.push_back(N->getFlags());\n Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));\n Record.push_back(N->getRuntimeLang());\n Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));\n Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));\n Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));\n\n Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDISubroutineType(\n const DISubroutineType *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n const unsigned HasNoOldTypeRefs = 0x2;\n Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());\n Record.push_back(N->getFlags());\n Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));\n Record.push_back(N->getCC());\n\n Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIFile(const DIFile *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));\n if (N->getRawChecksum()) {\n Record.push_back(N->getRawChecksum()->Kind);\n Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));\n } else {\n \/\/ Maintain backwards compatibility with the old internal representation of\n \/\/ CSK_None in ChecksumKind by writing nulls here when Checksum is None.\n Record.push_back(0);\n Record.push_back(VE.getMetadataOrNullID(nullptr));\n }\n auto Source = N->getRawSource();\n if (Source)\n Record.push_back(VE.getMetadataOrNullID(*Source));\n\n Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n assert(N->isDistinct() && \"Expected distinct compile units\");\n Record.push_back(\/* IsDistinct *\/ true);\n Record.push_back(N->getSourceLanguage());\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));\n Record.push_back(N->isOptimized());\n Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));\n Record.push_back(N->getRuntimeVersion());\n Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));\n Record.push_back(N->getEmissionKind());\n Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));\n Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));\n Record.push_back(\/* subprograms *\/ 0);\n Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));\n Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));\n Record.push_back(N->getDWOId());\n Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));\n Record.push_back(N->getSplitDebugInlining());\n Record.push_back(N->getDebugInfoForProfiling());\n Record.push_back((unsigned)N->getNameTableKind());\n Record.push_back(N->getRangesBaseAddress());\n Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));\n\n Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n const uint64_t HasUnitFlag = 1 << 1;\n const uint64_t HasSPFlagsFlag = 1 << 2;\n Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getType()));\n Record.push_back(N->getScopeLine());\n Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));\n Record.push_back(N->getSPFlags());\n Record.push_back(N->getVirtualIndex());\n Record.push_back(N->getFlags());\n Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));\n Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));\n Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));\n Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));\n Record.push_back(N->getThisAdjustment());\n Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));\n\n Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n Record.push_back(N->getColumn());\n\n Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDILexicalBlockFile(\n const DILexicalBlockFile *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getDiscriminator());\n\n Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getDecl()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLineNo());\n\n Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n\n Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(N->getMacinfoType());\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));\n\n Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(N->getMacinfoType());\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));\n\n Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.reserve(N->getArgs().size());\n for (ValueAsMetadata *MD : N->getArgs())\n Record.push_back(VE.getMetadataID(MD));\n\n Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIModule(const DIModule *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n for (auto &I : N->operands())\n Record.push_back(VE.getMetadataOrNullID(I));\n Record.push_back(N->getLineNo());\n Record.push_back(N->getIsDecl());\n\n Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDITemplateTypeParameter(\n const DITemplateTypeParameter *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getType()));\n Record.push_back(N->isDefault());\n\n Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDITemplateValueParameter(\n const DITemplateValueParameter *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(N->getTag());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getType()));\n Record.push_back(N->isDefault());\n Record.push_back(VE.getMetadataOrNullID(N->getValue()));\n\n Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIGlobalVariable(\n const DIGlobalVariable *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n const uint64_t Version = 2 << 1;\n Record.push_back((uint64_t)N->isDistinct() | Version);\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getType()));\n Record.push_back(N->isLocalToUnit());\n Record.push_back(N->isDefinition());\n Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));\n Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));\n Record.push_back(N->getAlignInBits());\n\n Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDILocalVariable(\n const DILocalVariable *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n \/\/ In order to support all possible bitcode formats in BitcodeReader we need\n \/\/ to distinguish the following cases:\n \/\/ 1) Record has no artificial tag (Record[1]),\n \/\/ has no obsolete inlinedAt field (Record[9]).\n \/\/ In this case Record size will be 8, HasAlignment flag is false.\n \/\/ 2) Record has artificial tag (Record[1]),\n \/\/ has no obsolete inlignedAt field (Record[9]).\n \/\/ In this case Record size will be 9, HasAlignment flag is false.\n \/\/ 3) Record has both artificial tag (Record[1]) and\n \/\/ obsolete inlignedAt field (Record[9]).\n \/\/ In this case Record size will be 10, HasAlignment flag is false.\n \/\/ 4) Record has neither artificial tag, nor inlignedAt field, but\n \/\/ HasAlignment flag is true and Record[8] contains alignment value.\n const uint64_t HasAlignmentFlag = 1 << 1;\n Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getType()));\n Record.push_back(N->getArg());\n Record.push_back(N->getFlags());\n Record.push_back(N->getAlignInBits());\n\n Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDILabel(\n const DILabel *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back((uint64_t)N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n\n Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.reserve(N->getElements().size() + 1);\n const uint64_t Version = 3 << 1;\n Record.push_back((uint64_t)N->isDistinct() | Version);\n Record.append(N->elements_begin(), N->elements_end());\n\n Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIGlobalVariableExpression(\n const DIGlobalVariableExpression *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getVariable()));\n Record.push_back(VE.getMetadataOrNullID(N->getExpression()));\n\n Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,\n SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getFile()));\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));\n Record.push_back(N->getAttributes());\n Record.push_back(VE.getMetadataOrNullID(N->getType()));\n\n Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);\n Record.clear();\n}\n\nvoid ModuleBitcodeWriter::writeDIImportedEntity(\n const DIImportedEntity *N, SmallVectorImpl &Record,\n unsigned Abbrev) {\n Record.push_back(N->isDistinct());\n Record.push_back(N->getTag());\n Record.push_back(VE.getMetadataOrNullID(N->getScope()));\n Record.push_back(VE.getMetadataOrNullID(N->getEntity()));\n Record.push_back(N->getLine());\n Record.push_back(VE.getMetadataOrNullID(N->getRawName()));\n Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));\n\n Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);\n Record.clear();\n}\n\nunsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));\n return Stream.EmitAbbrev(std::move(Abbv));\n}\n\nvoid ModuleBitcodeWriter::writeNamedMetadata(\n SmallVectorImpl &Record) {\n if (M.named_metadata_empty())\n return;\n\n unsigned Abbrev = createNamedMetadataAbbrev();\n for (const NamedMDNode &NMD : M.named_metadata()) {\n \/\/ Write name.\n StringRef Str = NMD.getName();\n Record.append(Str.bytes_begin(), Str.bytes_end());\n Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);\n Record.clear();\n\n \/\/ Write named metadata operands.\n for (const MDNode *N : NMD.operands())\n Record.push_back(VE.getMetadataID(N));\n Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);\n Record.clear();\n }\n}\n\nunsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ # of strings\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ offset to chars\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));\n return Stream.EmitAbbrev(std::move(Abbv));\n}\n\n\/\/\/ Write out a record for MDString.\n\/\/\/\n\/\/\/ All the metadata strings in a metadata block are emitted in a single\n\/\/\/ record. The sizes and strings themselves are shoved into a blob.\nvoid ModuleBitcodeWriter::writeMetadataStrings(\n ArrayRef Strings, SmallVectorImpl &Record) {\n if (Strings.empty())\n return;\n\n \/\/ Start the record with the number of strings.\n Record.push_back(bitc::METADATA_STRINGS);\n Record.push_back(Strings.size());\n\n \/\/ Emit the sizes of the strings in the blob.\n SmallString<256> Blob;\n {\n BitstreamWriter W(Blob);\n for (const Metadata *MD : Strings)\n W.EmitVBR(cast(MD)->getLength(), 6);\n W.FlushToWord();\n }\n\n \/\/ Add the offset to the strings to the record.\n Record.push_back(Blob.size());\n\n \/\/ Add the strings to the blob.\n for (const Metadata *MD : Strings)\n Blob.append(cast(MD)->getString());\n\n \/\/ Emit the final record.\n Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);\n Record.clear();\n}\n\n\/\/ Generates an enum to use as an index in the Abbrev array of Metadata record.\nenum MetadataAbbrev : unsigned {\n#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,\n#include \"llvm\/IR\/Metadata.def\"\n LastPlusOne\n};\n\nvoid ModuleBitcodeWriter::writeMetadataRecords(\n ArrayRef MDs, SmallVectorImpl &Record,\n std::vector *MDAbbrevs, std::vector *IndexPos) {\n if (MDs.empty())\n return;\n\n \/\/ Initialize MDNode abbreviations.\n#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;\n#include \"llvm\/IR\/Metadata.def\"\n\n for (const Metadata *MD : MDs) {\n if (IndexPos)\n IndexPos->push_back(Stream.GetCurrentBitNo());\n if (const MDNode *N = dyn_cast(MD)) {\n assert(N->isResolved() && \"Expected forward references to be resolved\");\n\n switch (N->getMetadataID()) {\n default:\n llvm_unreachable(\"Invalid MDNode subclass\");\n#define HANDLE_MDNODE_LEAF(CLASS) \\\n case Metadata::CLASS##Kind: \\\n if (MDAbbrevs) \\\n write##CLASS(cast(N), Record, \\\n (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \\\n else \\\n write##CLASS(cast(N), Record, CLASS##Abbrev); \\\n continue;\n#include \"llvm\/IR\/Metadata.def\"\n }\n }\n writeValueAsMetadata(cast(MD), Record);\n }\n}\n\nvoid ModuleBitcodeWriter::writeModuleMetadata() {\n if (!VE.hasMDs() && M.named_metadata_empty())\n return;\n\n Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);\n SmallVector Record;\n\n \/\/ Emit all abbrevs upfront, so that the reader can jump in the middle of the\n \/\/ block and load any metadata.\n std::vector MDAbbrevs;\n\n MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);\n MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();\n MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =\n createGenericDINodeAbbrev();\n\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Emit MDStrings together upfront.\n writeMetadataStrings(VE.getMDStrings(), Record);\n\n \/\/ We only emit an index for the metadata record if we have more than a given\n \/\/ (naive) threshold of metadatas, otherwise it is not worth it.\n if (VE.getNonMDStrings().size() > IndexThreshold) {\n \/\/ Write a placeholder value in for the offset of the metadata index,\n \/\/ which is written after the records, so that it can include\n \/\/ the offset of each entry. The placeholder offset will be\n \/\/ updated after all records are emitted.\n uint64_t Vals[] = {0, 0};\n Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);\n }\n\n \/\/ Compute and save the bit offset to the current position, which will be\n \/\/ patched when we emit the index later. We can simply subtract the 64-bit\n \/\/ fixed size from the current bit number to get the location to backpatch.\n uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();\n\n \/\/ This index will contain the bitpos for each individual record.\n std::vector IndexPos;\n IndexPos.reserve(VE.getNonMDStrings().size());\n\n \/\/ Write all the records\n writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);\n\n if (VE.getNonMDStrings().size() > IndexThreshold) {\n \/\/ Now that we have emitted all the records we will emit the index. But\n \/\/ first\n \/\/ backpatch the forward reference so that the reader can skip the records\n \/\/ efficiently.\n Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,\n Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);\n\n \/\/ Delta encode the index.\n uint64_t PreviousValue = IndexOffsetRecordBitPos;\n for (auto &Elt : IndexPos) {\n auto EltDelta = Elt - PreviousValue;\n PreviousValue = Elt;\n Elt = EltDelta;\n }\n \/\/ Emit the index record.\n Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);\n IndexPos.clear();\n }\n\n \/\/ Write the named metadata now.\n writeNamedMetadata(Record);\n\n auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {\n SmallVector Record;\n Record.push_back(VE.getValueID(&GO));\n pushGlobalMetadataAttachment(Record, GO);\n Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);\n };\n for (const Function &F : M)\n if (F.isDeclaration() && F.hasMetadata())\n AddDeclAttachedMetadata(F);\n \/\/ FIXME: Only store metadata for declarations here, and move data for global\n \/\/ variable definitions to a separate block (PR28134).\n for (const GlobalVariable &GV : M.globals())\n if (GV.hasMetadata())\n AddDeclAttachedMetadata(GV);\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {\n if (!VE.hasMDs())\n return;\n\n Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);\n SmallVector Record;\n writeMetadataStrings(VE.getMDStrings(), Record);\n writeMetadataRecords(VE.getNonMDStrings(), Record);\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::pushGlobalMetadataAttachment(\n SmallVectorImpl &Record, const GlobalObject &GO) {\n \/\/ [n x [id, mdnode]]\n SmallVector, 4> MDs;\n GO.getAllMetadata(MDs);\n for (const auto &I : MDs) {\n Record.push_back(I.first);\n Record.push_back(VE.getMetadataID(I.second));\n }\n}\n\nvoid ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {\n Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);\n\n SmallVector Record;\n\n if (F.hasMetadata()) {\n pushGlobalMetadataAttachment(Record, F);\n Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);\n Record.clear();\n }\n\n \/\/ Write metadata attachments\n \/\/ METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]\n SmallVector, 4> MDs;\n for (const BasicBlock &BB : F)\n for (const Instruction &I : BB) {\n MDs.clear();\n I.getAllMetadataOtherThanDebugLoc(MDs);\n\n \/\/ If no metadata, ignore instruction.\n if (MDs.empty()) continue;\n\n Record.push_back(VE.getInstructionID(&I));\n\n for (unsigned i = 0, e = MDs.size(); i != e; ++i) {\n Record.push_back(MDs[i].first);\n Record.push_back(VE.getMetadataID(MDs[i].second));\n }\n Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);\n Record.clear();\n }\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeModuleMetadataKinds() {\n SmallVector Record;\n\n \/\/ Write metadata kinds\n \/\/ METADATA_KIND - [n x [id, name]]\n SmallVector Names;\n M.getMDKindNames(Names);\n\n if (Names.empty()) return;\n\n Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);\n\n for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {\n Record.push_back(MDKindID);\n StringRef KName = Names[MDKindID];\n Record.append(KName.begin(), KName.end());\n\n Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);\n Record.clear();\n }\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeOperandBundleTags() {\n \/\/ Write metadata kinds\n \/\/\n \/\/ OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG\n \/\/\n \/\/ OPERAND_BUNDLE_TAG - [strchr x N]\n\n SmallVector Tags;\n M.getOperandBundleTags(Tags);\n\n if (Tags.empty())\n return;\n\n Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);\n\n SmallVector Record;\n\n for (auto Tag : Tags) {\n Record.append(Tag.begin(), Tag.end());\n\n Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);\n Record.clear();\n }\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeSyncScopeNames() {\n SmallVector SSNs;\n M.getContext().getSyncScopeNames(SSNs);\n if (SSNs.empty())\n return;\n\n Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);\n\n SmallVector Record;\n for (auto SSN : SSNs) {\n Record.append(SSN.begin(), SSN.end());\n Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);\n Record.clear();\n }\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,\n bool isGlobal) {\n if (FirstVal == LastVal) return;\n\n Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);\n\n unsigned AggregateAbbrev = 0;\n unsigned String8Abbrev = 0;\n unsigned CString7Abbrev = 0;\n unsigned CString6Abbrev = 0;\n \/\/ If this is a constant pool for the module, emit module-specific abbrevs.\n if (isGlobal) {\n \/\/ Abbrev for CST_CODE_AGGREGATE.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));\n AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for CST_CODE_STRING.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));\n String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));\n \/\/ Abbrev for CST_CODE_CSTRING.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));\n CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));\n \/\/ Abbrev for CST_CODE_CSTRING.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));\n CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));\n }\n\n SmallVector Record;\n\n const ValueEnumerator::ValueList &Vals = VE.getValues();\n Type *LastTy = nullptr;\n for (unsigned i = FirstVal; i != LastVal; ++i) {\n const Value *V = Vals[i].first;\n \/\/ If we need to switch types, do so now.\n if (V->getType() != LastTy) {\n LastTy = V->getType();\n Record.push_back(VE.getTypeID(LastTy));\n Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,\n CONSTANTS_SETTYPE_ABBREV);\n Record.clear();\n }\n\n if (const InlineAsm *IA = dyn_cast(V)) {\n Record.push_back(unsigned(IA->hasSideEffects()) |\n unsigned(IA->isAlignStack()) << 1 |\n unsigned(IA->getDialect()&1) << 2);\n\n \/\/ Add the asm string.\n const std::string &AsmStr = IA->getAsmString();\n Record.push_back(AsmStr.size());\n Record.append(AsmStr.begin(), AsmStr.end());\n\n \/\/ Add the constraint string.\n const std::string &ConstraintStr = IA->getConstraintString();\n Record.push_back(ConstraintStr.size());\n Record.append(ConstraintStr.begin(), ConstraintStr.end());\n Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);\n Record.clear();\n continue;\n }\n const Constant *C = cast(V);\n unsigned Code = -1U;\n unsigned AbbrevToUse = 0;\n if (C->isNullValue()) {\n Code = bitc::CST_CODE_NULL;\n } else if (isa(C)) {\n Code = bitc::CST_CODE_POISON;\n } else if (isa(C)) {\n Code = bitc::CST_CODE_UNDEF;\n } else if (const ConstantInt *IV = dyn_cast(C)) {\n if (IV->getBitWidth() <= 64) {\n uint64_t V = IV->getSExtValue();\n emitSignedInt64(Record, V);\n Code = bitc::CST_CODE_INTEGER;\n AbbrevToUse = CONSTANTS_INTEGER_ABBREV;\n } else { \/\/ Wide integers, > 64 bits in size.\n emitWideAPInt(Record, IV->getValue());\n Code = bitc::CST_CODE_WIDE_INTEGER;\n }\n } else if (const ConstantFP *CFP = dyn_cast(C)) {\n Code = bitc::CST_CODE_FLOAT;\n Type *Ty = CFP->getType();\n if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||\n Ty->isDoubleTy()) {\n Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());\n } else if (Ty->isX86_FP80Ty()) {\n \/\/ api needed to prevent premature destruction\n \/\/ bits are not in the same order as a normal i80 APInt, compensate.\n APInt api = CFP->getValueAPF().bitcastToAPInt();\n const uint64_t *p = api.getRawData();\n Record.push_back((p[1] << 48) | (p[0] >> 16));\n Record.push_back(p[0] & 0xffffLL);\n } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {\n APInt api = CFP->getValueAPF().bitcastToAPInt();\n const uint64_t *p = api.getRawData();\n Record.push_back(p[0]);\n Record.push_back(p[1]);\n } else {\n assert(0 && \"Unknown FP type!\");\n }\n } else if (isa(C) &&\n cast(C)->isString()) {\n const ConstantDataSequential *Str = cast(C);\n \/\/ Emit constant strings specially.\n unsigned NumElts = Str->getNumElements();\n \/\/ If this is a null-terminated string, use the denser CSTRING encoding.\n if (Str->isCString()) {\n Code = bitc::CST_CODE_CSTRING;\n --NumElts; \/\/ Don't encode the null, which isn't allowed by char6.\n } else {\n Code = bitc::CST_CODE_STRING;\n AbbrevToUse = String8Abbrev;\n }\n bool isCStr7 = Code == bitc::CST_CODE_CSTRING;\n bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;\n for (unsigned i = 0; i != NumElts; ++i) {\n unsigned char V = Str->getElementAsInteger(i);\n Record.push_back(V);\n isCStr7 &= (V & 128) == 0;\n if (isCStrChar6)\n isCStrChar6 = BitCodeAbbrevOp::isChar6(V);\n }\n\n if (isCStrChar6)\n AbbrevToUse = CString6Abbrev;\n else if (isCStr7)\n AbbrevToUse = CString7Abbrev;\n } else if (const ConstantDataSequential *CDS =\n dyn_cast(C)) {\n Code = bitc::CST_CODE_DATA;\n Type *EltTy = CDS->getElementType();\n if (isa(EltTy)) {\n for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)\n Record.push_back(CDS->getElementAsInteger(i));\n } else {\n for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)\n Record.push_back(\n CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());\n }\n } else if (isa(C)) {\n Code = bitc::CST_CODE_AGGREGATE;\n for (const Value *Op : C->operands())\n Record.push_back(VE.getValueID(Op));\n AbbrevToUse = AggregateAbbrev;\n } else if (const ConstantExpr *CE = dyn_cast(C)) {\n switch (CE->getOpcode()) {\n default:\n if (Instruction::isCast(CE->getOpcode())) {\n Code = bitc::CST_CODE_CE_CAST;\n Record.push_back(getEncodedCastOpcode(CE->getOpcode()));\n Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));\n Record.push_back(VE.getValueID(C->getOperand(0)));\n AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;\n } else {\n assert(CE->getNumOperands() == 2 && \"Unknown constant expr!\");\n Code = bitc::CST_CODE_CE_BINOP;\n Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));\n Record.push_back(VE.getValueID(C->getOperand(0)));\n Record.push_back(VE.getValueID(C->getOperand(1)));\n uint64_t Flags = getOptimizationFlags(CE);\n if (Flags != 0)\n Record.push_back(Flags);\n }\n break;\n case Instruction::FNeg: {\n assert(CE->getNumOperands() == 1 && \"Unknown constant expr!\");\n Code = bitc::CST_CODE_CE_UNOP;\n Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));\n Record.push_back(VE.getValueID(C->getOperand(0)));\n uint64_t Flags = getOptimizationFlags(CE);\n if (Flags != 0)\n Record.push_back(Flags);\n break;\n }\n case Instruction::GetElementPtr: {\n Code = bitc::CST_CODE_CE_GEP;\n const auto *GO = cast(C);\n Record.push_back(VE.getTypeID(GO->getSourceElementType()));\n if (Optional Idx = GO->getInRangeIndex()) {\n Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;\n Record.push_back((*Idx << 1) | GO->isInBounds());\n } else if (GO->isInBounds())\n Code = bitc::CST_CODE_CE_INBOUNDS_GEP;\n for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {\n Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));\n Record.push_back(VE.getValueID(C->getOperand(i)));\n }\n break;\n }\n case Instruction::Select:\n Code = bitc::CST_CODE_CE_SELECT;\n Record.push_back(VE.getValueID(C->getOperand(0)));\n Record.push_back(VE.getValueID(C->getOperand(1)));\n Record.push_back(VE.getValueID(C->getOperand(2)));\n break;\n case Instruction::ExtractElement:\n Code = bitc::CST_CODE_CE_EXTRACTELT;\n Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));\n Record.push_back(VE.getValueID(C->getOperand(0)));\n Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));\n Record.push_back(VE.getValueID(C->getOperand(1)));\n break;\n case Instruction::InsertElement:\n Code = bitc::CST_CODE_CE_INSERTELT;\n Record.push_back(VE.getValueID(C->getOperand(0)));\n Record.push_back(VE.getValueID(C->getOperand(1)));\n Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));\n Record.push_back(VE.getValueID(C->getOperand(2)));\n break;\n case Instruction::ShuffleVector:\n \/\/ If the return type and argument types are the same, this is a\n \/\/ standard shufflevector instruction. If the types are different,\n \/\/ then the shuffle is widening or truncating the input vectors, and\n \/\/ the argument type must also be encoded.\n if (C->getType() == C->getOperand(0)->getType()) {\n Code = bitc::CST_CODE_CE_SHUFFLEVEC;\n } else {\n Code = bitc::CST_CODE_CE_SHUFVEC_EX;\n Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));\n }\n Record.push_back(VE.getValueID(C->getOperand(0)));\n Record.push_back(VE.getValueID(C->getOperand(1)));\n Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));\n break;\n case Instruction::ICmp:\n case Instruction::FCmp:\n Code = bitc::CST_CODE_CE_CMP;\n Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));\n Record.push_back(VE.getValueID(C->getOperand(0)));\n Record.push_back(VE.getValueID(C->getOperand(1)));\n Record.push_back(CE->getPredicate());\n break;\n }\n } else if (const BlockAddress *BA = dyn_cast(C)) {\n Code = bitc::CST_CODE_BLOCKADDRESS;\n Record.push_back(VE.getTypeID(BA->getFunction()->getType()));\n Record.push_back(VE.getValueID(BA->getFunction()));\n Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));\n } else if (const auto *Equiv = dyn_cast(C)) {\n Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;\n Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));\n Record.push_back(VE.getValueID(Equiv->getGlobalValue()));\n } else {\n#ifndef NDEBUG\n C->dump();\n#endif\n llvm_unreachable(\"Unknown constant!\");\n }\n Stream.EmitRecord(Code, Record, AbbrevToUse);\n Record.clear();\n }\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeModuleConstants() {\n const ValueEnumerator::ValueList &Vals = VE.getValues();\n\n \/\/ Find the first constant to emit, which is the first non-globalvalue value.\n \/\/ We know globalvalues have been emitted by WriteModuleInfo.\n for (unsigned i = 0, e = Vals.size(); i != e; ++i) {\n if (!isa(Vals[i].first)) {\n writeConstants(i, Vals.size(), true);\n return;\n }\n }\n}\n\n\/\/\/ pushValueAndType - The file has to encode both the value and type id for\n\/\/\/ many values, because we need to know what type to create for forward\n\/\/\/ references. However, most operands are not forward references, so this type\n\/\/\/ field is not needed.\n\/\/\/\n\/\/\/ This function adds V's value ID to Vals. If the value ID is higher than the\n\/\/\/ instruction ID, then it is a forward reference, and it also includes the\n\/\/\/ type ID. The value ID that is written is encoded relative to the InstID.\nbool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,\n SmallVectorImpl &Vals) {\n unsigned ValID = VE.getValueID(V);\n \/\/ Make encoding relative to the InstID.\n Vals.push_back(InstID - ValID);\n if (ValID >= InstID) {\n Vals.push_back(VE.getTypeID(V->getType()));\n return true;\n }\n return false;\n}\n\nvoid ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,\n unsigned InstID) {\n SmallVector Record;\n LLVMContext &C = CS.getContext();\n\n for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {\n const auto &Bundle = CS.getOperandBundleAt(i);\n Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));\n\n for (auto &Input : Bundle.Inputs)\n pushValueAndType(Input, InstID, Record);\n\n Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);\n Record.clear();\n }\n}\n\n\/\/\/ pushValue - Like pushValueAndType, but where the type of the value is\n\/\/\/ omitted (perhaps it was already encoded in an earlier operand).\nvoid ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,\n SmallVectorImpl &Vals) {\n unsigned ValID = VE.getValueID(V);\n Vals.push_back(InstID - ValID);\n}\n\nvoid ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,\n SmallVectorImpl &Vals) {\n unsigned ValID = VE.getValueID(V);\n int64_t diff = ((int32_t)InstID - (int32_t)ValID);\n emitSignedInt64(Vals, diff);\n}\n\n\/\/\/ WriteInstruction - Emit an instruction to the specified stream.\nvoid ModuleBitcodeWriter::writeInstruction(const Instruction &I,\n unsigned InstID,\n SmallVectorImpl &Vals) {\n unsigned Code = 0;\n unsigned AbbrevToUse = 0;\n VE.setInstructionID(&I);\n switch (I.getOpcode()) {\n default:\n if (Instruction::isCast(I.getOpcode())) {\n Code = bitc::FUNC_CODE_INST_CAST;\n if (!pushValueAndType(I.getOperand(0), InstID, Vals))\n AbbrevToUse = FUNCTION_INST_CAST_ABBREV;\n Vals.push_back(VE.getTypeID(I.getType()));\n Vals.push_back(getEncodedCastOpcode(I.getOpcode()));\n } else {\n assert(isa(I) && \"Unknown instruction!\");\n Code = bitc::FUNC_CODE_INST_BINOP;\n if (!pushValueAndType(I.getOperand(0), InstID, Vals))\n AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;\n pushValue(I.getOperand(1), InstID, Vals);\n Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));\n uint64_t Flags = getOptimizationFlags(&I);\n if (Flags != 0) {\n if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)\n AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;\n Vals.push_back(Flags);\n }\n }\n break;\n case Instruction::FNeg: {\n Code = bitc::FUNC_CODE_INST_UNOP;\n if (!pushValueAndType(I.getOperand(0), InstID, Vals))\n AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;\n Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));\n uint64_t Flags = getOptimizationFlags(&I);\n if (Flags != 0) {\n if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)\n AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;\n Vals.push_back(Flags);\n }\n break;\n }\n case Instruction::GetElementPtr: {\n Code = bitc::FUNC_CODE_INST_GEP;\n AbbrevToUse = FUNCTION_INST_GEP_ABBREV;\n auto &GEPInst = cast(I);\n Vals.push_back(GEPInst.isInBounds());\n Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));\n for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)\n pushValueAndType(I.getOperand(i), InstID, Vals);\n break;\n }\n case Instruction::ExtractValue: {\n Code = bitc::FUNC_CODE_INST_EXTRACTVAL;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n const ExtractValueInst *EVI = cast(&I);\n Vals.append(EVI->idx_begin(), EVI->idx_end());\n break;\n }\n case Instruction::InsertValue: {\n Code = bitc::FUNC_CODE_INST_INSERTVAL;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n pushValueAndType(I.getOperand(1), InstID, Vals);\n const InsertValueInst *IVI = cast(&I);\n Vals.append(IVI->idx_begin(), IVI->idx_end());\n break;\n }\n case Instruction::Select: {\n Code = bitc::FUNC_CODE_INST_VSELECT;\n pushValueAndType(I.getOperand(1), InstID, Vals);\n pushValue(I.getOperand(2), InstID, Vals);\n pushValueAndType(I.getOperand(0), InstID, Vals);\n uint64_t Flags = getOptimizationFlags(&I);\n if (Flags != 0)\n Vals.push_back(Flags);\n break;\n }\n case Instruction::ExtractElement:\n Code = bitc::FUNC_CODE_INST_EXTRACTELT;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n pushValueAndType(I.getOperand(1), InstID, Vals);\n break;\n case Instruction::InsertElement:\n Code = bitc::FUNC_CODE_INST_INSERTELT;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n pushValue(I.getOperand(1), InstID, Vals);\n pushValueAndType(I.getOperand(2), InstID, Vals);\n break;\n case Instruction::ShuffleVector:\n Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n pushValue(I.getOperand(1), InstID, Vals);\n pushValue(cast(I).getShuffleMaskForBitcode(), InstID,\n Vals);\n break;\n case Instruction::ICmp:\n case Instruction::FCmp: {\n \/\/ compare returning Int1Ty or vector of Int1Ty\n Code = bitc::FUNC_CODE_INST_CMP2;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n pushValue(I.getOperand(1), InstID, Vals);\n Vals.push_back(cast(I).getPredicate());\n uint64_t Flags = getOptimizationFlags(&I);\n if (Flags != 0)\n Vals.push_back(Flags);\n break;\n }\n\n case Instruction::Ret:\n {\n Code = bitc::FUNC_CODE_INST_RET;\n unsigned NumOperands = I.getNumOperands();\n if (NumOperands == 0)\n AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;\n else if (NumOperands == 1) {\n if (!pushValueAndType(I.getOperand(0), InstID, Vals))\n AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;\n } else {\n for (unsigned i = 0, e = NumOperands; i != e; ++i)\n pushValueAndType(I.getOperand(i), InstID, Vals);\n }\n }\n break;\n case Instruction::Br:\n {\n Code = bitc::FUNC_CODE_INST_BR;\n const BranchInst &II = cast(I);\n Vals.push_back(VE.getValueID(II.getSuccessor(0)));\n if (II.isConditional()) {\n Vals.push_back(VE.getValueID(II.getSuccessor(1)));\n pushValue(II.getCondition(), InstID, Vals);\n }\n }\n break;\n case Instruction::Switch:\n {\n Code = bitc::FUNC_CODE_INST_SWITCH;\n const SwitchInst &SI = cast(I);\n Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));\n pushValue(SI.getCondition(), InstID, Vals);\n Vals.push_back(VE.getValueID(SI.getDefaultDest()));\n for (auto Case : SI.cases()) {\n Vals.push_back(VE.getValueID(Case.getCaseValue()));\n Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));\n }\n }\n break;\n case Instruction::IndirectBr:\n Code = bitc::FUNC_CODE_INST_INDIRECTBR;\n Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));\n \/\/ Encode the address operand as relative, but not the basic blocks.\n pushValue(I.getOperand(0), InstID, Vals);\n for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)\n Vals.push_back(VE.getValueID(I.getOperand(i)));\n break;\n\n case Instruction::Invoke: {\n const InvokeInst *II = cast(&I);\n const Value *Callee = II->getCalledOperand();\n FunctionType *FTy = II->getFunctionType();\n\n if (II->hasOperandBundles())\n writeOperandBundles(*II, InstID);\n\n Code = bitc::FUNC_CODE_INST_INVOKE;\n\n Vals.push_back(VE.getAttributeListID(II->getAttributes()));\n Vals.push_back(II->getCallingConv() | 1 << 13);\n Vals.push_back(VE.getValueID(II->getNormalDest()));\n Vals.push_back(VE.getValueID(II->getUnwindDest()));\n Vals.push_back(VE.getTypeID(FTy));\n pushValueAndType(Callee, InstID, Vals);\n\n \/\/ Emit value #'s for the fixed parameters.\n for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)\n pushValue(I.getOperand(i), InstID, Vals); \/\/ fixed param.\n\n \/\/ Emit type\/value pairs for varargs params.\n if (FTy->isVarArg()) {\n for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();\n i != e; ++i)\n pushValueAndType(I.getOperand(i), InstID, Vals); \/\/ vararg\n }\n break;\n }\n case Instruction::Resume:\n Code = bitc::FUNC_CODE_INST_RESUME;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n break;\n case Instruction::CleanupRet: {\n Code = bitc::FUNC_CODE_INST_CLEANUPRET;\n const auto &CRI = cast(I);\n pushValue(CRI.getCleanupPad(), InstID, Vals);\n if (CRI.hasUnwindDest())\n Vals.push_back(VE.getValueID(CRI.getUnwindDest()));\n break;\n }\n case Instruction::CatchRet: {\n Code = bitc::FUNC_CODE_INST_CATCHRET;\n const auto &CRI = cast(I);\n pushValue(CRI.getCatchPad(), InstID, Vals);\n Vals.push_back(VE.getValueID(CRI.getSuccessor()));\n break;\n }\n case Instruction::CleanupPad:\n case Instruction::CatchPad: {\n const auto &FuncletPad = cast(I);\n Code = isa(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD\n : bitc::FUNC_CODE_INST_CLEANUPPAD;\n pushValue(FuncletPad.getParentPad(), InstID, Vals);\n\n unsigned NumArgOperands = FuncletPad.getNumArgOperands();\n Vals.push_back(NumArgOperands);\n for (unsigned Op = 0; Op != NumArgOperands; ++Op)\n pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);\n break;\n }\n case Instruction::CatchSwitch: {\n Code = bitc::FUNC_CODE_INST_CATCHSWITCH;\n const auto &CatchSwitch = cast(I);\n\n pushValue(CatchSwitch.getParentPad(), InstID, Vals);\n\n unsigned NumHandlers = CatchSwitch.getNumHandlers();\n Vals.push_back(NumHandlers);\n for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())\n Vals.push_back(VE.getValueID(CatchPadBB));\n\n if (CatchSwitch.hasUnwindDest())\n Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));\n break;\n }\n case Instruction::CallBr: {\n const CallBrInst *CBI = cast(&I);\n const Value *Callee = CBI->getCalledOperand();\n FunctionType *FTy = CBI->getFunctionType();\n\n if (CBI->hasOperandBundles())\n writeOperandBundles(*CBI, InstID);\n\n Code = bitc::FUNC_CODE_INST_CALLBR;\n\n Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));\n\n Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |\n 1 << bitc::CALL_EXPLICIT_TYPE);\n\n Vals.push_back(VE.getValueID(CBI->getDefaultDest()));\n Vals.push_back(CBI->getNumIndirectDests());\n for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)\n Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));\n\n Vals.push_back(VE.getTypeID(FTy));\n pushValueAndType(Callee, InstID, Vals);\n\n \/\/ Emit value #'s for the fixed parameters.\n for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)\n pushValue(I.getOperand(i), InstID, Vals); \/\/ fixed param.\n\n \/\/ Emit type\/value pairs for varargs params.\n if (FTy->isVarArg()) {\n for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands();\n i != e; ++i)\n pushValueAndType(I.getOperand(i), InstID, Vals); \/\/ vararg\n }\n break;\n }\n case Instruction::Unreachable:\n Code = bitc::FUNC_CODE_INST_UNREACHABLE;\n AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;\n break;\n\n case Instruction::PHI: {\n const PHINode &PN = cast(I);\n Code = bitc::FUNC_CODE_INST_PHI;\n \/\/ With the newer instruction encoding, forward references could give\n \/\/ negative valued IDs. This is most common for PHIs, so we use\n \/\/ signed VBRs.\n SmallVector Vals64;\n Vals64.push_back(VE.getTypeID(PN.getType()));\n for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {\n pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);\n Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));\n }\n\n uint64_t Flags = getOptimizationFlags(&I);\n if (Flags != 0)\n Vals64.push_back(Flags);\n\n \/\/ Emit a Vals64 vector and exit.\n Stream.EmitRecord(Code, Vals64, AbbrevToUse);\n Vals64.clear();\n return;\n }\n\n case Instruction::LandingPad: {\n const LandingPadInst &LP = cast(I);\n Code = bitc::FUNC_CODE_INST_LANDINGPAD;\n Vals.push_back(VE.getTypeID(LP.getType()));\n Vals.push_back(LP.isCleanup());\n Vals.push_back(LP.getNumClauses());\n for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {\n if (LP.isCatch(I))\n Vals.push_back(LandingPadInst::Catch);\n else\n Vals.push_back(LandingPadInst::Filter);\n pushValueAndType(LP.getClause(I), InstID, Vals);\n }\n break;\n }\n\n case Instruction::Alloca: {\n Code = bitc::FUNC_CODE_INST_ALLOCA;\n const AllocaInst &AI = cast(I);\n Vals.push_back(VE.getTypeID(AI.getAllocatedType()));\n Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));\n Vals.push_back(VE.getValueID(I.getOperand(0))); \/\/ size.\n using APV = AllocaPackedValues;\n unsigned Record = 0;\n Bitfield::set(Record, getEncodedAlign(AI.getAlign()));\n Bitfield::set(Record, AI.isUsedWithInAlloca());\n Bitfield::set(Record, true);\n Bitfield::set(Record, AI.isSwiftError());\n Vals.push_back(Record);\n break;\n }\n\n case Instruction::Load:\n if (cast(I).isAtomic()) {\n Code = bitc::FUNC_CODE_INST_LOADATOMIC;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n } else {\n Code = bitc::FUNC_CODE_INST_LOAD;\n if (!pushValueAndType(I.getOperand(0), InstID, Vals)) \/\/ ptr\n AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;\n }\n Vals.push_back(VE.getTypeID(I.getType()));\n Vals.push_back(getEncodedAlign(cast(I).getAlign()));\n Vals.push_back(cast(I).isVolatile());\n if (cast(I).isAtomic()) {\n Vals.push_back(getEncodedOrdering(cast(I).getOrdering()));\n Vals.push_back(getEncodedSyncScopeID(cast(I).getSyncScopeID()));\n }\n break;\n case Instruction::Store:\n if (cast(I).isAtomic())\n Code = bitc::FUNC_CODE_INST_STOREATOMIC;\n else\n Code = bitc::FUNC_CODE_INST_STORE;\n pushValueAndType(I.getOperand(1), InstID, Vals); \/\/ ptrty + ptr\n pushValueAndType(I.getOperand(0), InstID, Vals); \/\/ valty + val\n Vals.push_back(getEncodedAlign(cast(I).getAlign()));\n Vals.push_back(cast(I).isVolatile());\n if (cast(I).isAtomic()) {\n Vals.push_back(getEncodedOrdering(cast(I).getOrdering()));\n Vals.push_back(\n getEncodedSyncScopeID(cast(I).getSyncScopeID()));\n }\n break;\n case Instruction::AtomicCmpXchg:\n Code = bitc::FUNC_CODE_INST_CMPXCHG;\n pushValueAndType(I.getOperand(0), InstID, Vals); \/\/ ptrty + ptr\n pushValueAndType(I.getOperand(1), InstID, Vals); \/\/ cmp.\n pushValue(I.getOperand(2), InstID, Vals); \/\/ newval.\n Vals.push_back(cast(I).isVolatile());\n Vals.push_back(\n getEncodedOrdering(cast(I).getSuccessOrdering()));\n Vals.push_back(\n getEncodedSyncScopeID(cast(I).getSyncScopeID()));\n Vals.push_back(\n getEncodedOrdering(cast(I).getFailureOrdering()));\n Vals.push_back(cast(I).isWeak());\n Vals.push_back(getEncodedAlign(cast(I).getAlign()));\n break;\n case Instruction::AtomicRMW:\n Code = bitc::FUNC_CODE_INST_ATOMICRMW;\n pushValueAndType(I.getOperand(0), InstID, Vals); \/\/ ptrty + ptr\n pushValue(I.getOperand(1), InstID, Vals); \/\/ val.\n Vals.push_back(\n getEncodedRMWOperation(cast(I).getOperation()));\n Vals.push_back(cast(I).isVolatile());\n Vals.push_back(getEncodedOrdering(cast(I).getOrdering()));\n Vals.push_back(\n getEncodedSyncScopeID(cast(I).getSyncScopeID()));\n Vals.push_back(getEncodedAlign(cast(I).getAlign()));\n break;\n case Instruction::Fence:\n Code = bitc::FUNC_CODE_INST_FENCE;\n Vals.push_back(getEncodedOrdering(cast(I).getOrdering()));\n Vals.push_back(getEncodedSyncScopeID(cast(I).getSyncScopeID()));\n break;\n case Instruction::Call: {\n const CallInst &CI = cast(I);\n FunctionType *FTy = CI.getFunctionType();\n\n if (CI.hasOperandBundles())\n writeOperandBundles(CI, InstID);\n\n Code = bitc::FUNC_CODE_INST_CALL;\n\n Vals.push_back(VE.getAttributeListID(CI.getAttributes()));\n\n unsigned Flags = getOptimizationFlags(&I);\n Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |\n unsigned(CI.isTailCall()) << bitc::CALL_TAIL |\n unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |\n 1 << bitc::CALL_EXPLICIT_TYPE |\n unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |\n unsigned(Flags != 0) << bitc::CALL_FMF);\n if (Flags != 0)\n Vals.push_back(Flags);\n\n Vals.push_back(VE.getTypeID(FTy));\n pushValueAndType(CI.getCalledOperand(), InstID, Vals); \/\/ Callee\n\n \/\/ Emit value #'s for the fixed parameters.\n for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {\n \/\/ Check for labels (can happen with asm labels).\n if (FTy->getParamType(i)->isLabelTy())\n Vals.push_back(VE.getValueID(CI.getArgOperand(i)));\n else\n pushValue(CI.getArgOperand(i), InstID, Vals); \/\/ fixed param.\n }\n\n \/\/ Emit type\/value pairs for varargs params.\n if (FTy->isVarArg()) {\n for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();\n i != e; ++i)\n pushValueAndType(CI.getArgOperand(i), InstID, Vals); \/\/ varargs\n }\n break;\n }\n case Instruction::VAArg:\n Code = bitc::FUNC_CODE_INST_VAARG;\n Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); \/\/ valistty\n pushValue(I.getOperand(0), InstID, Vals); \/\/ valist.\n Vals.push_back(VE.getTypeID(I.getType())); \/\/ restype.\n break;\n case Instruction::Freeze:\n Code = bitc::FUNC_CODE_INST_FREEZE;\n pushValueAndType(I.getOperand(0), InstID, Vals);\n break;\n }\n\n Stream.EmitRecord(Code, Vals, AbbrevToUse);\n Vals.clear();\n}\n\n\/\/\/ Write a GlobalValue VST to the module. The purpose of this data structure is\n\/\/\/ to allow clients to efficiently find the function body.\nvoid ModuleBitcodeWriter::writeGlobalValueSymbolTable(\n DenseMap &FunctionToBitcodeIndex) {\n \/\/ Get the offset of the VST we are writing, and backpatch it into\n \/\/ the VST forward declaration record.\n uint64_t VSTOffset = Stream.GetCurrentBitNo();\n \/\/ The BitcodeStartBit was the stream offset of the identification block.\n VSTOffset -= bitcodeStartBit();\n assert((VSTOffset & 31) == 0 && \"VST block not 32-bit aligned\");\n \/\/ Note that we add 1 here because the offset is relative to one word\n \/\/ before the start of the identification block, which was historically\n \/\/ always the start of the regular bitcode header.\n Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset \/ 32 + 1);\n\n Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);\n\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ value id\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ funcoffset\n unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n for (const Function &F : M) {\n uint64_t Record[2];\n\n if (F.isDeclaration())\n continue;\n\n Record[0] = VE.getValueID(&F);\n\n \/\/ Save the word offset of the function (from the start of the\n \/\/ actual bitcode written to the stream).\n uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();\n assert((BitcodeIndex & 31) == 0 && \"function block not 32-bit aligned\");\n \/\/ Note that we add 1 here because the offset is relative to one word\n \/\/ before the start of the identification block, which was historically\n \/\/ always the start of the regular bitcode header.\n Record[1] = BitcodeIndex \/ 32 + 1;\n\n Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);\n }\n\n Stream.ExitBlock();\n}\n\n\/\/\/ Emit names for arguments, instructions and basic blocks in a function.\nvoid ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(\n const ValueSymbolTable &VST) {\n if (VST.empty())\n return;\n\n Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);\n\n \/\/ FIXME: Set up the abbrev, we know how many values there are!\n \/\/ FIXME: We know if the type names can use 7-bit ascii.\n SmallVector NameVals;\n\n for (const ValueName &Name : VST) {\n \/\/ Figure out the encoding to use for the name.\n StringEncoding Bits = getStringEncoding(Name.getKey());\n\n unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;\n NameVals.push_back(VE.getValueID(Name.getValue()));\n\n \/\/ VST_CODE_ENTRY: [valueid, namechar x N]\n \/\/ VST_CODE_BBENTRY: [bbid, namechar x N]\n unsigned Code;\n if (isa(Name.getValue())) {\n Code = bitc::VST_CODE_BBENTRY;\n if (Bits == SE_Char6)\n AbbrevToUse = VST_BBENTRY_6_ABBREV;\n } else {\n Code = bitc::VST_CODE_ENTRY;\n if (Bits == SE_Char6)\n AbbrevToUse = VST_ENTRY_6_ABBREV;\n else if (Bits == SE_Fixed7)\n AbbrevToUse = VST_ENTRY_7_ABBREV;\n }\n\n for (const auto P : Name.getKey())\n NameVals.push_back((unsigned char)P);\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(Code, NameVals, AbbrevToUse);\n NameVals.clear();\n }\n\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {\n assert(Order.Shuffle.size() >= 2 && \"Shuffle too small\");\n unsigned Code;\n if (isa(Order.V))\n Code = bitc::USELIST_CODE_BB;\n else\n Code = bitc::USELIST_CODE_DEFAULT;\n\n SmallVector Record(Order.Shuffle.begin(), Order.Shuffle.end());\n Record.push_back(VE.getValueID(Order.V));\n Stream.EmitRecord(Code, Record);\n}\n\nvoid ModuleBitcodeWriter::writeUseListBlock(const Function *F) {\n assert(VE.shouldPreserveUseListOrder() &&\n \"Expected to be preserving use-list order\");\n\n auto hasMore = [&]() {\n return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;\n };\n if (!hasMore())\n \/\/ Nothing to do.\n return;\n\n Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);\n while (hasMore()) {\n writeUseList(std::move(VE.UseListOrders.back()));\n VE.UseListOrders.pop_back();\n }\n Stream.ExitBlock();\n}\n\n\/\/\/ Emit a function body to the module stream.\nvoid ModuleBitcodeWriter::writeFunction(\n const Function &F,\n DenseMap &FunctionToBitcodeIndex) {\n \/\/ Save the bitcode index of the start of this function block for recording\n \/\/ in the VST.\n FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();\n\n Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);\n VE.incorporateFunction(F);\n\n SmallVector Vals;\n\n \/\/ Emit the number of basic blocks, so the reader can create them ahead of\n \/\/ time.\n Vals.push_back(VE.getBasicBlocks().size());\n Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);\n Vals.clear();\n\n \/\/ If there are function-local constants, emit them now.\n unsigned CstStart, CstEnd;\n VE.getFunctionConstantRange(CstStart, CstEnd);\n writeConstants(CstStart, CstEnd, false);\n\n \/\/ If there is function-local metadata, emit it now.\n writeFunctionMetadata(F);\n\n \/\/ Keep a running idea of what the instruction ID is.\n unsigned InstID = CstEnd;\n\n bool NeedsMetadataAttachment = F.hasMetadata();\n\n DILocation *LastDL = nullptr;\n \/\/ Finally, emit all the instructions, in order.\n for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)\n for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();\n I != E; ++I) {\n writeInstruction(*I, InstID, Vals);\n\n if (!I->getType()->isVoidTy())\n ++InstID;\n\n \/\/ If the instruction has metadata, write a metadata attachment later.\n NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();\n\n \/\/ If the instruction has a debug location, emit it.\n DILocation *DL = I->getDebugLoc();\n if (!DL)\n continue;\n\n if (DL == LastDL) {\n \/\/ Just repeat the same debug loc as last time.\n Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);\n continue;\n }\n\n Vals.push_back(DL->getLine());\n Vals.push_back(DL->getColumn());\n Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));\n Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));\n Vals.push_back(DL->isImplicitCode());\n Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);\n Vals.clear();\n\n LastDL = DL;\n }\n\n \/\/ Emit names for all the instructions etc.\n if (auto *Symtab = F.getValueSymbolTable())\n writeFunctionLevelValueSymbolTable(*Symtab);\n\n if (NeedsMetadataAttachment)\n writeFunctionMetadataAttachment(F);\n if (VE.shouldPreserveUseListOrder())\n writeUseListBlock(&F);\n VE.purgeFunction();\n Stream.ExitBlock();\n}\n\n\/\/ Emit blockinfo, which defines the standard abbreviations etc.\nvoid ModuleBitcodeWriter::writeBlockInfo() {\n \/\/ We only want to emit block info records for blocks that have multiple\n \/\/ instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.\n \/\/ Other blocks can define their abbrevs inline.\n Stream.EnterBlockInfoBlock();\n\n { \/\/ 8-bit fixed-width VST_CODE_ENTRY\/VST_CODE_BBENTRY strings.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));\n if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=\n VST_ENTRY_8_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n\n { \/\/ 7-bit fixed width VST_CODE_ENTRY strings.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));\n if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=\n VST_ENTRY_7_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ 6-bit char6 VST_CODE_ENTRY strings.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));\n if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=\n VST_ENTRY_6_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ 6-bit char6 VST_CODE_BBENTRY strings.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));\n if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=\n VST_BBENTRY_6_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n\n { \/\/ SETTYPE abbrev for CONSTANTS_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,\n VE.computeBitsRequiredForTypeIndicies()));\n if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=\n CONSTANTS_SETTYPE_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n\n { \/\/ INTEGER abbrev for CONSTANTS_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=\n CONSTANTS_INTEGER_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n\n { \/\/ CE_CAST abbrev for CONSTANTS_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); \/\/ cast opc\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, \/\/ typeid\n VE.computeBitsRequiredForTypeIndicies()));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ value id\n\n if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=\n CONSTANTS_CE_CAST_Abbrev)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ NULL abbrev for CONSTANTS_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));\n if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=\n CONSTANTS_NULL_Abbrev)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n\n \/\/ FIXME: This should only use space for first class types!\n\n { \/\/ INST_LOAD abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ Ptr\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, \/\/ dest ty\n VE.computeBitsRequiredForTypeIndicies()));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ Align\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); \/\/ volatile\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_LOAD_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ INST_UNOP abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ LHS\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); \/\/ opc\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_UNOP_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ LHS\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); \/\/ opc\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); \/\/ flags\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_UNOP_FLAGS_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ INST_BINOP abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ LHS\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ RHS\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); \/\/ opc\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_BINOP_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ LHS\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ RHS\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); \/\/ opc\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); \/\/ flags\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_BINOP_FLAGS_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ INST_CAST abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ OpVal\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, \/\/ dest ty\n VE.computeBitsRequiredForTypeIndicies()));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); \/\/ opc\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_CAST_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n\n { \/\/ INST_RET abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_RET_VOID_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ INST_RET abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ ValID\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_RET_VAL_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n { \/\/ INST_UNREACHABLE abbrev for FUNCTION_BLOCK.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_UNREACHABLE_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n {\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, \/\/ dest ty\n Log2_32_Ceil(VE.getTypes().size() + 1)));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=\n FUNCTION_INST_GEP_ABBREV)\n llvm_unreachable(\"Unexpected abbrev ordering!\");\n }\n\n Stream.ExitBlock();\n}\n\n\/\/\/ Write the module path strings, currently only used when generating\n\/\/\/ a combined index file.\nvoid IndexBitcodeWriter::writeModStrings() {\n Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);\n\n \/\/ TODO: See which abbrev sizes we actually need to emit\n\n \/\/ 8-bit fixed-width MST_ENTRY strings.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));\n unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ 7-bit fixed width MST_ENTRY strings.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));\n unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ 6-bit char6 MST_ENTRY strings.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));\n unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));\n unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));\n\n SmallVector Vals;\n forEachModule(\n [&](const StringMapEntry> &MPSE) {\n StringRef Key = MPSE.getKey();\n const auto &Value = MPSE.getValue();\n StringEncoding Bits = getStringEncoding(Key);\n unsigned AbbrevToUse = Abbrev8Bit;\n if (Bits == SE_Char6)\n AbbrevToUse = Abbrev6Bit;\n else if (Bits == SE_Fixed7)\n AbbrevToUse = Abbrev7Bit;\n\n Vals.push_back(Value.first);\n Vals.append(Key.begin(), Key.end());\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);\n\n \/\/ Emit an optional hash for the module now\n const auto &Hash = Value.second;\n if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {\n Vals.assign(Hash.begin(), Hash.end());\n \/\/ Emit the hash record.\n Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);\n }\n\n Vals.clear();\n });\n Stream.ExitBlock();\n}\n\n\/\/\/ Write the function type metadata related records that need to appear before\n\/\/\/ a function summary entry (whether per-module or combined).\ntemplate \nstatic void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,\n FunctionSummary *FS,\n Fn GetValueID) {\n if (!FS->type_tests().empty())\n Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());\n\n SmallVector Record;\n\n auto WriteVFuncIdVec = [&](uint64_t Ty,\n ArrayRef VFs) {\n if (VFs.empty())\n return;\n Record.clear();\n for (auto &VF : VFs) {\n Record.push_back(VF.GUID);\n Record.push_back(VF.Offset);\n }\n Stream.EmitRecord(Ty, Record);\n };\n\n WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,\n FS->type_test_assume_vcalls());\n WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,\n FS->type_checked_load_vcalls());\n\n auto WriteConstVCallVec = [&](uint64_t Ty,\n ArrayRef VCs) {\n for (auto &VC : VCs) {\n Record.clear();\n Record.push_back(VC.VFunc.GUID);\n Record.push_back(VC.VFunc.Offset);\n llvm::append_range(Record, VC.Args);\n Stream.EmitRecord(Ty, Record);\n }\n };\n\n WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,\n FS->type_test_assume_const_vcalls());\n WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,\n FS->type_checked_load_const_vcalls());\n\n auto WriteRange = [&](ConstantRange Range) {\n Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);\n assert(Range.getLower().getNumWords() == 1);\n assert(Range.getUpper().getNumWords() == 1);\n emitSignedInt64(Record, *Range.getLower().getRawData());\n emitSignedInt64(Record, *Range.getUpper().getRawData());\n };\n\n if (!FS->paramAccesses().empty()) {\n Record.clear();\n for (auto &Arg : FS->paramAccesses()) {\n size_t UndoSize = Record.size();\n Record.push_back(Arg.ParamNo);\n WriteRange(Arg.Use);\n Record.push_back(Arg.Calls.size());\n for (auto &Call : Arg.Calls) {\n Record.push_back(Call.ParamNo);\n Optional ValueID = GetValueID(Call.Callee);\n if (!ValueID) {\n \/\/ If ValueID is unknown we can't drop just this call, we must drop\n \/\/ entire parameter.\n Record.resize(UndoSize);\n break;\n }\n Record.push_back(*ValueID);\n WriteRange(Call.Offsets);\n }\n }\n if (!Record.empty())\n Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);\n }\n}\n\n\/\/\/ Collect type IDs from type tests used by function.\nstatic void\ngetReferencedTypeIds(FunctionSummary *FS,\n std::set &ReferencedTypeIds) {\n if (!FS->type_tests().empty())\n for (auto &TT : FS->type_tests())\n ReferencedTypeIds.insert(TT);\n\n auto GetReferencedTypesFromVFuncIdVec =\n [&](ArrayRef VFs) {\n for (auto &VF : VFs)\n ReferencedTypeIds.insert(VF.GUID);\n };\n\n GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());\n GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());\n\n auto GetReferencedTypesFromConstVCallVec =\n [&](ArrayRef VCs) {\n for (auto &VC : VCs)\n ReferencedTypeIds.insert(VC.VFunc.GUID);\n };\n\n GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());\n GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());\n}\n\nstatic void writeWholeProgramDevirtResolutionByArg(\n SmallVector &NameVals, const std::vector &args,\n const WholeProgramDevirtResolution::ByArg &ByArg) {\n NameVals.push_back(args.size());\n llvm::append_range(NameVals, args);\n\n NameVals.push_back(ByArg.TheKind);\n NameVals.push_back(ByArg.Info);\n NameVals.push_back(ByArg.Byte);\n NameVals.push_back(ByArg.Bit);\n}\n\nstatic void writeWholeProgramDevirtResolution(\n SmallVector &NameVals, StringTableBuilder &StrtabBuilder,\n uint64_t Id, const WholeProgramDevirtResolution &Wpd) {\n NameVals.push_back(Id);\n\n NameVals.push_back(Wpd.TheKind);\n NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));\n NameVals.push_back(Wpd.SingleImplName.size());\n\n NameVals.push_back(Wpd.ResByArg.size());\n for (auto &A : Wpd.ResByArg)\n writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);\n}\n\nstatic void writeTypeIdSummaryRecord(SmallVector &NameVals,\n StringTableBuilder &StrtabBuilder,\n const std::string &Id,\n const TypeIdSummary &Summary) {\n NameVals.push_back(StrtabBuilder.add(Id));\n NameVals.push_back(Id.size());\n\n NameVals.push_back(Summary.TTRes.TheKind);\n NameVals.push_back(Summary.TTRes.SizeM1BitWidth);\n NameVals.push_back(Summary.TTRes.AlignLog2);\n NameVals.push_back(Summary.TTRes.SizeM1);\n NameVals.push_back(Summary.TTRes.BitMask);\n NameVals.push_back(Summary.TTRes.InlineBits);\n\n for (auto &W : Summary.WPDRes)\n writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,\n W.second);\n}\n\nstatic void writeTypeIdCompatibleVtableSummaryRecord(\n SmallVector &NameVals, StringTableBuilder &StrtabBuilder,\n const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,\n ValueEnumerator &VE) {\n NameVals.push_back(StrtabBuilder.add(Id));\n NameVals.push_back(Id.size());\n\n for (auto &P : Summary) {\n NameVals.push_back(P.AddressPointOffset);\n NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));\n }\n}\n\n\/\/ Helper to emit a single function summary record.\nvoid ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(\n SmallVector &NameVals, GlobalValueSummary *Summary,\n unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,\n const Function &F) {\n NameVals.push_back(ValueID);\n\n FunctionSummary *FS = cast(Summary);\n\n writeFunctionTypeMetadataRecords(\n Stream, FS, [&](const ValueInfo &VI) -> Optional {\n return {VE.getValueID(VI.getValue())};\n });\n\n auto SpecialRefCnts = FS->specialRefCounts();\n NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));\n NameVals.push_back(FS->instCount());\n NameVals.push_back(getEncodedFFlags(FS->fflags()));\n NameVals.push_back(FS->refs().size());\n NameVals.push_back(SpecialRefCnts.first); \/\/ rorefcnt\n NameVals.push_back(SpecialRefCnts.second); \/\/ worefcnt\n\n for (auto &RI : FS->refs())\n NameVals.push_back(VE.getValueID(RI.getValue()));\n\n bool HasProfileData =\n F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;\n for (auto &ECI : FS->calls()) {\n NameVals.push_back(getValueId(ECI.first));\n if (HasProfileData)\n NameVals.push_back(static_cast(ECI.second.Hotness));\n else if (WriteRelBFToSummary)\n NameVals.push_back(ECI.second.RelBlockFreq);\n }\n\n unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);\n unsigned Code =\n (HasProfileData ? bitc::FS_PERMODULE_PROFILE\n : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF\n : bitc::FS_PERMODULE));\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(Code, NameVals, FSAbbrev);\n NameVals.clear();\n}\n\n\/\/ Collect the global value references in the given variable's initializer,\n\/\/ and emit them in a summary record.\nvoid ModuleBitcodeWriterBase::writeModuleLevelReferences(\n const GlobalVariable &V, SmallVector &NameVals,\n unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {\n auto VI = Index->getValueInfo(V.getGUID());\n if (!VI || VI.getSummaryList().empty()) {\n \/\/ Only declarations should not have a summary (a declaration might however\n \/\/ have a summary if the def was in module level asm).\n assert(V.isDeclaration());\n return;\n }\n auto *Summary = VI.getSummaryList()[0].get();\n NameVals.push_back(VE.getValueID(&V));\n GlobalVarSummary *VS = cast(Summary);\n NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));\n NameVals.push_back(getEncodedGVarFlags(VS->varflags()));\n\n auto VTableFuncs = VS->vTableFuncs();\n if (!VTableFuncs.empty())\n NameVals.push_back(VS->refs().size());\n\n unsigned SizeBeforeRefs = NameVals.size();\n for (auto &RI : VS->refs())\n NameVals.push_back(VE.getValueID(RI.getValue()));\n \/\/ Sort the refs for determinism output, the vector returned by FS->refs() has\n \/\/ been initialized from a DenseSet.\n llvm::sort(drop_begin(NameVals, SizeBeforeRefs));\n\n if (VTableFuncs.empty())\n Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,\n FSModRefsAbbrev);\n else {\n \/\/ VTableFuncs pairs should already be sorted by offset.\n for (auto &P : VTableFuncs) {\n NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));\n NameVals.push_back(P.VTableOffset);\n }\n\n Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,\n FSModVTableRefsAbbrev);\n }\n NameVals.clear();\n}\n\n\/\/\/ Emit the per-module summary section alongside the rest of\n\/\/\/ the module's bitcode.\nvoid ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {\n \/\/ By default we compile with ThinLTO if the module has a summary, but the\n \/\/ client can request full LTO with a module flag.\n bool IsThinLTO = true;\n if (auto *MD =\n mdconst::extract_or_null(M.getModuleFlag(\"ThinLTO\")))\n IsThinLTO = MD->getZExtValue();\n Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID\n : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,\n 4);\n\n Stream.EmitRecord(\n bitc::FS_VERSION,\n ArrayRef{ModuleSummaryIndex::BitcodeSummaryVersion});\n\n \/\/ Write the index flags.\n uint64_t Flags = 0;\n \/\/ Bits 1-3 are set only in the combined index, skip them.\n if (Index->enableSplitLTOUnit())\n Flags |= 0x8;\n Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef{Flags});\n\n if (Index->begin() == Index->end()) {\n Stream.ExitBlock();\n return;\n }\n\n for (const auto &GVI : valueIds()) {\n Stream.EmitRecord(bitc::FS_VALUE_GUID,\n ArrayRef{GVI.second, GVI.first});\n }\n\n \/\/ Abbrev for FS_PERMODULE_PROFILE.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ instcount\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ fflags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ numrefs\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ rorefcnt\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ worefcnt\n \/\/ numrefs x valueid, n x (valueid, hotness)\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.\n Abbv = std::make_shared();\n if (WriteRelBFToSummary)\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));\n else\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ instcount\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ fflags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ numrefs\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ rorefcnt\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ worefcnt\n \/\/ numrefs x valueid, n x (valueid [, rel_block_freq])\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); \/\/ valueids\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ numrefs\n \/\/ numrefs x valueid, n x (valueid , offset)\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_ALIAS.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_TYPE_ID_METADATA\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ typeid strtab index\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ typeid length\n \/\/ n x (valueid , offset)\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n SmallVector NameVals;\n \/\/ Iterate over the list of functions instead of the Index to\n \/\/ ensure the ordering is stable.\n for (const Function &F : M) {\n \/\/ Summary emission does not support anonymous functions, they have to\n \/\/ renamed using the anonymous function renaming pass.\n if (!F.hasName())\n report_fatal_error(\"Unexpected anonymous function when writing summary\");\n\n ValueInfo VI = Index->getValueInfo(F.getGUID());\n if (!VI || VI.getSummaryList().empty()) {\n \/\/ Only declarations should not have a summary (a declaration might\n \/\/ however have a summary if the def was in module level asm).\n assert(F.isDeclaration());\n continue;\n }\n auto *Summary = VI.getSummaryList()[0].get();\n writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),\n FSCallsAbbrev, FSCallsProfileAbbrev, F);\n }\n\n \/\/ Capture references from GlobalVariable initializers, which are outside\n \/\/ of a function scope.\n for (const GlobalVariable &G : M.globals())\n writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,\n FSModVTableRefsAbbrev);\n\n for (const GlobalAlias &A : M.aliases()) {\n auto *Aliasee = A.getBaseObject();\n if (!Aliasee->hasName())\n \/\/ Nameless function don't have an entry in the summary, skip it.\n continue;\n auto AliasId = VE.getValueID(&A);\n auto AliaseeId = VE.getValueID(Aliasee);\n NameVals.push_back(AliasId);\n auto *Summary = Index->getGlobalValueSummary(A);\n AliasSummary *AS = cast(Summary);\n NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));\n NameVals.push_back(AliaseeId);\n Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);\n NameVals.clear();\n }\n\n for (auto &S : Index->typeIdCompatibleVtableMap()) {\n writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,\n S.second, VE);\n Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,\n TypeIdCompatibleVtableAbbrev);\n NameVals.clear();\n }\n\n Stream.EmitRecord(bitc::FS_BLOCK_COUNT,\n ArrayRef{Index->getBlockCount()});\n\n Stream.ExitBlock();\n}\n\n\/\/\/ Emit the combined summary section into the combined index file.\nvoid IndexBitcodeWriter::writeCombinedGlobalValueSummary() {\n Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);\n Stream.EmitRecord(\n bitc::FS_VERSION,\n ArrayRef{ModuleSummaryIndex::BitcodeSummaryVersion});\n\n \/\/ Write the index flags.\n Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef{Index.getFlags()});\n\n for (const auto &GVI : valueIds()) {\n Stream.EmitRecord(bitc::FS_VALUE_GUID,\n ArrayRef{GVI.second, GVI.first});\n }\n\n \/\/ Abbrev for FS_COMBINED.\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ modid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ instcount\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ fflags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ entrycount\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ numrefs\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ rorefcnt\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ worefcnt\n \/\/ numrefs x valueid, n x (valueid)\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_COMBINED_PROFILE.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ modid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ instcount\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ fflags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ entrycount\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ numrefs\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ rorefcnt\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); \/\/ worefcnt\n \/\/ numrefs x valueid, n x (valueid, hotness)\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ modid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); \/\/ valueids\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));\n unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ Abbrev for FS_COMBINED_ALIAS.\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ modid\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); \/\/ flags\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); \/\/ valueid\n unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n \/\/ The aliases are emitted as a post-pass, and will point to the value\n \/\/ id of the aliasee. Save them in a vector for post-processing.\n SmallVector Aliases;\n\n \/\/ Save the value id for each summary for alias emission.\n DenseMap SummaryToValueIdMap;\n\n SmallVector NameVals;\n\n \/\/ Set that will be populated during call to writeFunctionTypeMetadataRecords\n \/\/ with the type ids referenced by this index file.\n std::set ReferencedTypeIds;\n\n \/\/ For local linkage, we also emit the original name separately\n \/\/ immediately after the record.\n auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {\n if (!GlobalValue::isLocalLinkage(S.linkage()))\n return;\n NameVals.push_back(S.getOriginalName());\n Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);\n NameVals.clear();\n };\n\n std::set DefOrUseGUIDs;\n forEachSummary([&](GVInfo I, bool IsAliasee) {\n GlobalValueSummary *S = I.second;\n assert(S);\n DefOrUseGUIDs.insert(I.first);\n for (const ValueInfo &VI : S->refs())\n DefOrUseGUIDs.insert(VI.getGUID());\n\n auto ValueId = getValueId(I.first);\n assert(ValueId);\n SummaryToValueIdMap[S] = *ValueId;\n\n \/\/ If this is invoked for an aliasee, we want to record the above\n \/\/ mapping, but then not emit a summary entry (if the aliasee is\n \/\/ to be imported, we will invoke this separately with IsAliasee=false).\n if (IsAliasee)\n return;\n\n if (auto *AS = dyn_cast(S)) {\n \/\/ Will process aliases as a post-pass because the reader wants all\n \/\/ global to be loaded first.\n Aliases.push_back(AS);\n return;\n }\n\n if (auto *VS = dyn_cast(S)) {\n NameVals.push_back(*ValueId);\n NameVals.push_back(Index.getModuleId(VS->modulePath()));\n NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));\n NameVals.push_back(getEncodedGVarFlags(VS->varflags()));\n for (auto &RI : VS->refs()) {\n auto RefValueId = getValueId(RI.getGUID());\n if (!RefValueId)\n continue;\n NameVals.push_back(*RefValueId);\n }\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,\n FSModRefsAbbrev);\n NameVals.clear();\n MaybeEmitOriginalName(*S);\n return;\n }\n\n auto GetValueId = [&](const ValueInfo &VI) -> Optional {\n GlobalValue::GUID GUID = VI.getGUID();\n Optional CallValueId = getValueId(GUID);\n if (CallValueId)\n return CallValueId;\n \/\/ For SamplePGO, the indirect call targets for local functions will\n \/\/ have its original name annotated in profile. We try to find the\n \/\/ corresponding PGOFuncName as the GUID.\n GUID = Index.getGUIDFromOriginalID(GUID);\n if (!GUID)\n return None;\n CallValueId = getValueId(GUID);\n if (!CallValueId)\n return None;\n \/\/ The mapping from OriginalId to GUID may return a GUID\n \/\/ that corresponds to a static variable. Filter it out here.\n \/\/ This can happen when\n \/\/ 1) There is a call to a library function which does not have\n \/\/ a CallValidId;\n \/\/ 2) There is a static variable with the OriginalGUID identical\n \/\/ to the GUID of the library function in 1);\n \/\/ When this happens, the logic for SamplePGO kicks in and\n \/\/ the static variable in 2) will be found, which needs to be\n \/\/ filtered out.\n auto *GVSum = Index.getGlobalValueSummary(GUID, false);\n if (GVSum && GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)\n return None;\n return CallValueId;\n };\n\n auto *FS = cast(S);\n writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);\n getReferencedTypeIds(FS, ReferencedTypeIds);\n\n NameVals.push_back(*ValueId);\n NameVals.push_back(Index.getModuleId(FS->modulePath()));\n NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));\n NameVals.push_back(FS->instCount());\n NameVals.push_back(getEncodedFFlags(FS->fflags()));\n NameVals.push_back(FS->entryCount());\n\n \/\/ Fill in below\n NameVals.push_back(0); \/\/ numrefs\n NameVals.push_back(0); \/\/ rorefcnt\n NameVals.push_back(0); \/\/ worefcnt\n\n unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;\n for (auto &RI : FS->refs()) {\n auto RefValueId = getValueId(RI.getGUID());\n if (!RefValueId)\n continue;\n NameVals.push_back(*RefValueId);\n if (RI.isReadOnly())\n RORefCnt++;\n else if (RI.isWriteOnly())\n WORefCnt++;\n Count++;\n }\n NameVals[6] = Count;\n NameVals[7] = RORefCnt;\n NameVals[8] = WORefCnt;\n\n bool HasProfileData = false;\n for (auto &EI : FS->calls()) {\n HasProfileData |=\n EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;\n if (HasProfileData)\n break;\n }\n\n for (auto &EI : FS->calls()) {\n \/\/ If this GUID doesn't have a value id, it doesn't have a function\n \/\/ summary and we don't need to record any calls to it.\n Optional CallValueId = GetValueId(EI.first);\n if (!CallValueId)\n continue;\n NameVals.push_back(*CallValueId);\n if (HasProfileData)\n NameVals.push_back(static_cast(EI.second.Hotness));\n }\n\n unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);\n unsigned Code =\n (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(Code, NameVals, FSAbbrev);\n NameVals.clear();\n MaybeEmitOriginalName(*S);\n });\n\n for (auto *AS : Aliases) {\n auto AliasValueId = SummaryToValueIdMap[AS];\n assert(AliasValueId);\n NameVals.push_back(AliasValueId);\n NameVals.push_back(Index.getModuleId(AS->modulePath()));\n NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));\n auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];\n assert(AliaseeValueId);\n NameVals.push_back(AliaseeValueId);\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);\n NameVals.clear();\n MaybeEmitOriginalName(*AS);\n\n if (auto *FS = dyn_cast(&AS->getAliasee()))\n getReferencedTypeIds(FS, ReferencedTypeIds);\n }\n\n if (!Index.cfiFunctionDefs().empty()) {\n for (auto &S : Index.cfiFunctionDefs()) {\n if (DefOrUseGUIDs.count(\n GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {\n NameVals.push_back(StrtabBuilder.add(S));\n NameVals.push_back(S.size());\n }\n }\n if (!NameVals.empty()) {\n Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);\n NameVals.clear();\n }\n }\n\n if (!Index.cfiFunctionDecls().empty()) {\n for (auto &S : Index.cfiFunctionDecls()) {\n if (DefOrUseGUIDs.count(\n GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {\n NameVals.push_back(StrtabBuilder.add(S));\n NameVals.push_back(S.size());\n }\n }\n if (!NameVals.empty()) {\n Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);\n NameVals.clear();\n }\n }\n\n \/\/ Walk the GUIDs that were referenced, and write the\n \/\/ corresponding type id records.\n for (auto &T : ReferencedTypeIds) {\n auto TidIter = Index.typeIds().equal_range(T);\n for (auto It = TidIter.first; It != TidIter.second; ++It) {\n writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,\n It->second.second);\n Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);\n NameVals.clear();\n }\n }\n\n Stream.EmitRecord(bitc::FS_BLOCK_COUNT,\n ArrayRef{Index.getBlockCount()});\n\n Stream.ExitBlock();\n}\n\n\/\/\/ Create the \"IDENTIFICATION_BLOCK_ID\" containing a single string with the\n\/\/\/ current llvm version, and a record for the epoch number.\nstatic void writeIdentificationBlock(BitstreamWriter &Stream) {\n Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);\n\n \/\/ Write the \"user readable\" string identifying the bitcode producer\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));\n auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,\n \"LLVM\" LLVM_VERSION_STRING, StringAbbrev);\n\n \/\/ Write the epoch version\n Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));\n auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n constexpr std::array Vals = {{bitc::BITCODE_CURRENT_EPOCH}};\n Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);\n Stream.ExitBlock();\n}\n\nvoid ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {\n \/\/ Emit the module's hash.\n \/\/ MODULE_CODE_HASH: [5*i32]\n if (GenerateHash) {\n uint32_t Vals[5];\n Hasher.update(ArrayRef((const uint8_t *)&(Buffer)[BlockStartPos],\n Buffer.size() - BlockStartPos));\n StringRef Hash = Hasher.result();\n for (int Pos = 0; Pos < 20; Pos += 4) {\n Vals[Pos \/ 4] = support::endian::read32be(Hash.data() + Pos);\n }\n\n \/\/ Emit the finished record.\n Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);\n\n if (ModHash)\n \/\/ Save the written hash value.\n llvm::copy(Vals, std::begin(*ModHash));\n }\n}\n\nvoid ModuleBitcodeWriter::write() {\n writeIdentificationBlock(Stream);\n\n Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);\n size_t BlockStartPos = Buffer.size();\n\n writeModuleVersion();\n\n \/\/ Emit blockinfo, which defines the standard abbreviations etc.\n writeBlockInfo();\n\n \/\/ Emit information describing all of the types in the module.\n writeTypeTable();\n\n \/\/ Emit information about attribute groups.\n writeAttributeGroupTable();\n\n \/\/ Emit information about parameter attributes.\n writeAttributeTable();\n\n writeComdats();\n\n \/\/ Emit top-level description of module, including target triple, inline asm,\n \/\/ descriptors for global variables, and function prototype info.\n writeModuleInfo();\n\n \/\/ Emit constants.\n writeModuleConstants();\n\n \/\/ Emit metadata kind names.\n writeModuleMetadataKinds();\n\n \/\/ Emit metadata.\n writeModuleMetadata();\n\n \/\/ Emit module-level use-lists.\n if (VE.shouldPreserveUseListOrder())\n writeUseListBlock(nullptr);\n\n writeOperandBundleTags();\n writeSyncScopeNames();\n\n \/\/ Emit function bodies.\n DenseMap FunctionToBitcodeIndex;\n for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)\n if (!F->isDeclaration())\n writeFunction(*F, FunctionToBitcodeIndex);\n\n \/\/ Need to write after the above call to WriteFunction which populates\n \/\/ the summary information in the index.\n if (Index)\n writePerModuleGlobalValueSummary();\n\n writeGlobalValueSymbolTable(FunctionToBitcodeIndex);\n\n writeModuleHash(BlockStartPos);\n\n Stream.ExitBlock();\n}\n\nstatic void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl &Buffer,\n uint32_t &Position) {\n support::endian::write32le(&Buffer[Position], Value);\n Position += 4;\n}\n\n\/\/\/ If generating a bc file on darwin, we have to emit a\n\/\/\/ header and trailer to make it compatible with the system archiver. To do\n\/\/\/ this we emit the following header, and then emit a trailer that pads the\n\/\/\/ file out to be a multiple of 16 bytes.\n\/\/\/\n\/\/\/ struct bc_header {\n\/\/\/ uint32_t Magic; \/\/ 0x0B17C0DE\n\/\/\/ uint32_t Version; \/\/ Version, currently always 0.\n\/\/\/ uint32_t BitcodeOffset; \/\/ Offset to traditional bitcode file.\n\/\/\/ uint32_t BitcodeSize; \/\/ Size of traditional bitcode file.\n\/\/\/ uint32_t CPUType; \/\/ CPU specifier.\n\/\/\/ ... potentially more later ...\n\/\/\/ };\nstatic void emitDarwinBCHeaderAndTrailer(SmallVectorImpl &Buffer,\n const Triple &TT) {\n unsigned CPUType = ~0U;\n\n \/\/ Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,\n \/\/ armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic\n \/\/ number from \/usr\/include\/mach\/machine.h. It is ok to reproduce the\n \/\/ specific constants here because they are implicitly part of the Darwin ABI.\n enum {\n DARWIN_CPU_ARCH_ABI64 = 0x01000000,\n DARWIN_CPU_TYPE_X86 = 7,\n DARWIN_CPU_TYPE_ARM = 12,\n DARWIN_CPU_TYPE_POWERPC = 18\n };\n\n Triple::ArchType Arch = TT.getArch();\n if (Arch == Triple::x86_64)\n CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;\n else if (Arch == Triple::x86)\n CPUType = DARWIN_CPU_TYPE_X86;\n else if (Arch == Triple::ppc)\n CPUType = DARWIN_CPU_TYPE_POWERPC;\n else if (Arch == Triple::ppc64)\n CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;\n else if (Arch == Triple::arm || Arch == Triple::thumb)\n CPUType = DARWIN_CPU_TYPE_ARM;\n\n \/\/ Traditional Bitcode starts after header.\n assert(Buffer.size() >= BWH_HeaderSize &&\n \"Expected header size to be reserved\");\n unsigned BCOffset = BWH_HeaderSize;\n unsigned BCSize = Buffer.size() - BWH_HeaderSize;\n\n \/\/ Write the magic and version.\n unsigned Position = 0;\n writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);\n writeInt32ToBuffer(0, Buffer, Position); \/\/ Version.\n writeInt32ToBuffer(BCOffset, Buffer, Position);\n writeInt32ToBuffer(BCSize, Buffer, Position);\n writeInt32ToBuffer(CPUType, Buffer, Position);\n\n \/\/ If the file is not a multiple of 16 bytes, insert dummy padding.\n while (Buffer.size() & 15)\n Buffer.push_back(0);\n}\n\n\/\/\/ Helper to write the header common to all bitcode files.\nstatic void writeBitcodeHeader(BitstreamWriter &Stream) {\n \/\/ Emit the file header.\n Stream.Emit((unsigned)'B', 8);\n Stream.Emit((unsigned)'C', 8);\n Stream.Emit(0x0, 4);\n Stream.Emit(0xC, 4);\n Stream.Emit(0xE, 4);\n Stream.Emit(0xD, 4);\n}\n\nBitcodeWriter::BitcodeWriter(SmallVectorImpl &Buffer, raw_fd_stream *FS)\n : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {\n writeBitcodeHeader(*Stream);\n}\n\nBitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }\n\nvoid BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {\n Stream->EnterSubblock(Block, 3);\n\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(Record));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));\n auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));\n\n Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef{Record}, Blob);\n\n Stream->ExitBlock();\n}\n\nvoid BitcodeWriter::writeSymtab() {\n assert(!WroteStrtab && !WroteSymtab);\n\n \/\/ If any module has module-level inline asm, we will require a registered asm\n \/\/ parser for the target so that we can create an accurate symbol table for\n \/\/ the module.\n for (Module *M : Mods) {\n if (M->getModuleInlineAsm().empty())\n continue;\n\n std::string Err;\n const Triple TT(M->getTargetTriple());\n const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);\n if (!T || !T->hasMCAsmParser())\n return;\n }\n\n WroteSymtab = true;\n SmallVector Symtab;\n \/\/ The irsymtab::build function may be unable to create a symbol table if the\n \/\/ module is malformed (e.g. it contains an invalid alias). Writing a symbol\n \/\/ table is not required for correctness, but we still want to be able to\n \/\/ write malformed modules to bitcode files, so swallow the error.\n if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {\n consumeError(std::move(E));\n return;\n }\n\n writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,\n {Symtab.data(), Symtab.size()});\n}\n\nvoid BitcodeWriter::writeStrtab() {\n assert(!WroteStrtab);\n\n std::vector Strtab;\n StrtabBuilder.finalizeInOrder();\n Strtab.resize(StrtabBuilder.getSize());\n StrtabBuilder.write((uint8_t *)Strtab.data());\n\n writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,\n {Strtab.data(), Strtab.size()});\n\n WroteStrtab = true;\n}\n\nvoid BitcodeWriter::copyStrtab(StringRef Strtab) {\n writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);\n WroteStrtab = true;\n}\n\nvoid BitcodeWriter::writeModule(const Module &M,\n bool ShouldPreserveUseListOrder,\n const ModuleSummaryIndex *Index,\n bool GenerateHash, ModuleHash *ModHash) {\n assert(!WroteStrtab);\n\n \/\/ The Mods vector is used by irsymtab::build, which requires non-const\n \/\/ Modules in case it needs to materialize metadata. But the bitcode writer\n \/\/ requires that the module is materialized, so we can cast to non-const here,\n \/\/ after checking that it is in fact materialized.\n assert(M.isMaterialized());\n Mods.push_back(const_cast(&M));\n\n ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,\n ShouldPreserveUseListOrder, Index,\n GenerateHash, ModHash);\n ModuleWriter.write();\n}\n\nvoid BitcodeWriter::writeIndex(\n const ModuleSummaryIndex *Index,\n const std::map *ModuleToSummariesForIndex) {\n IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,\n ModuleToSummariesForIndex);\n IndexWriter.write();\n}\n\n\/\/\/ Write the specified module to the specified output stream.\nvoid llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,\n bool ShouldPreserveUseListOrder,\n const ModuleSummaryIndex *Index,\n bool GenerateHash, ModuleHash *ModHash) {\n SmallVector Buffer;\n Buffer.reserve(256*1024);\n\n \/\/ If this is darwin or another generic macho target, reserve space for the\n \/\/ header.\n Triple TT(M.getTargetTriple());\n if (TT.isOSDarwin() || TT.isOSBinFormatMachO())\n Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);\n\n BitcodeWriter Writer(Buffer, dyn_cast(&Out));\n Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,\n ModHash);\n Writer.writeSymtab();\n Writer.writeStrtab();\n\n if (TT.isOSDarwin() || TT.isOSBinFormatMachO())\n emitDarwinBCHeaderAndTrailer(Buffer, TT);\n\n \/\/ Write the generated bitstream to \"Out\".\n if (!Buffer.empty())\n Out.write((char *)&Buffer.front(), Buffer.size());\n}\n\nvoid IndexBitcodeWriter::write() {\n Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);\n\n writeModuleVersion();\n\n \/\/ Write the module paths in the combined index.\n writeModStrings();\n\n \/\/ Write the summary combined index records.\n writeCombinedGlobalValueSummary();\n\n Stream.ExitBlock();\n}\n\n\/\/ Write the specified module summary index to the given raw output stream,\n\/\/ where it will be written in a new bitcode block. This is used when\n\/\/ writing the combined index file for ThinLTO. When writing a subset of the\n\/\/ index for a distributed backend, provide a \\p ModuleToSummariesForIndex map.\nvoid llvm::WriteIndexToFile(\n const ModuleSummaryIndex &Index, raw_ostream &Out,\n const std::map *ModuleToSummariesForIndex) {\n SmallVector Buffer;\n Buffer.reserve(256 * 1024);\n\n BitcodeWriter Writer(Buffer);\n Writer.writeIndex(&Index, ModuleToSummariesForIndex);\n Writer.writeStrtab();\n\n Out.write((char *)&Buffer.front(), Buffer.size());\n}\n\nnamespace {\n\n\/\/\/ Class to manage the bitcode writing for a thin link bitcode file.\nclass ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {\n \/\/\/ ModHash is for use in ThinLTO incremental build, generated while writing\n \/\/\/ the module bitcode file.\n const ModuleHash *ModHash;\n\npublic:\n ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,\n BitstreamWriter &Stream,\n const ModuleSummaryIndex &Index,\n const ModuleHash &ModHash)\n : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,\n \/*ShouldPreserveUseListOrder=*\/false, &Index),\n ModHash(&ModHash) {}\n\n void write();\n\nprivate:\n void writeSimplifiedModuleInfo();\n};\n\n} \/\/ end anonymous namespace\n\n\/\/ This function writes a simpilified module info for thin link bitcode file.\n\/\/ It only contains the source file name along with the name(the offset and\n\/\/ size in strtab) and linkage for global values. For the global value info\n\/\/ entry, in order to keep linkage at offset 5, there are three zeros used\n\/\/ as padding.\nvoid ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {\n SmallVector Vals;\n \/\/ Emit the module's source file name.\n {\n StringEncoding Bits = getStringEncoding(M.getSourceFileName());\n BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);\n if (Bits == SE_Char6)\n AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);\n else if (Bits == SE_Fixed7)\n AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);\n\n \/\/ MODULE_CODE_SOURCE_FILENAME: [namechar x N]\n auto Abbv = std::make_shared();\n Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));\n Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));\n Abbv->Add(AbbrevOpToUse);\n unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));\n\n for (const auto P : M.getSourceFileName())\n Vals.push_back((unsigned char)P);\n\n Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);\n Vals.clear();\n }\n\n \/\/ Emit the global variable information.\n for (const GlobalVariable &GV : M.globals()) {\n \/\/ GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]\n Vals.push_back(StrtabBuilder.add(GV.getName()));\n Vals.push_back(GV.getName().size());\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(getEncodedLinkage(GV));\n\n Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);\n Vals.clear();\n }\n\n \/\/ Emit the function proto information.\n for (const Function &F : M) {\n \/\/ FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]\n Vals.push_back(StrtabBuilder.add(F.getName()));\n Vals.push_back(F.getName().size());\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(getEncodedLinkage(F));\n\n Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);\n Vals.clear();\n }\n\n \/\/ Emit the alias information.\n for (const GlobalAlias &A : M.aliases()) {\n \/\/ ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]\n Vals.push_back(StrtabBuilder.add(A.getName()));\n Vals.push_back(A.getName().size());\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(getEncodedLinkage(A));\n\n Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);\n Vals.clear();\n }\n\n \/\/ Emit the ifunc information.\n for (const GlobalIFunc &I : M.ifuncs()) {\n \/\/ IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]\n Vals.push_back(StrtabBuilder.add(I.getName()));\n Vals.push_back(I.getName().size());\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(0);\n Vals.push_back(getEncodedLinkage(I));\n\n Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);\n Vals.clear();\n }\n}\n\nvoid ThinLinkBitcodeWriter::write() {\n Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);\n\n writeModuleVersion();\n\n writeSimplifiedModuleInfo();\n\n writePerModuleGlobalValueSummary();\n\n \/\/ Write module hash.\n Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef(*ModHash));\n\n Stream.ExitBlock();\n}\n\nvoid BitcodeWriter::writeThinLinkBitcode(const Module &M,\n const ModuleSummaryIndex &Index,\n const ModuleHash &ModHash) {\n assert(!WroteStrtab);\n\n \/\/ The Mods vector is used by irsymtab::build, which requires non-const\n \/\/ Modules in case it needs to materialize metadata. But the bitcode writer\n \/\/ requires that the module is materialized, so we can cast to non-const here,\n \/\/ after checking that it is in fact materialized.\n assert(M.isMaterialized());\n Mods.push_back(const_cast(&M));\n\n ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,\n ModHash);\n ThinLinkWriter.write();\n}\n\n\/\/ Write the specified thin link bitcode file to the given raw output stream,\n\/\/ where it will be written in a new bitcode block. This is used when\n\/\/ writing the per-module index file for ThinLTO.\nvoid llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,\n const ModuleSummaryIndex &Index,\n const ModuleHash &ModHash) {\n SmallVector Buffer;\n Buffer.reserve(256 * 1024);\n\n BitcodeWriter Writer(Buffer);\n Writer.writeThinLinkBitcode(M, Index, ModHash);\n Writer.writeSymtab();\n Writer.writeStrtab();\n\n Out.write((char *)&Buffer.front(), Buffer.size());\n}\n\nstatic const char *getSectionNameForBitcode(const Triple &T) {\n switch (T.getObjectFormat()) {\n case Triple::MachO:\n return \"__LLVM,__bitcode\";\n case Triple::COFF:\n case Triple::ELF:\n case Triple::Wasm:\n case Triple::UnknownObjectFormat:\n return \".llvmbc\";\n case Triple::GOFF:\n llvm_unreachable(\"GOFF is not yet implemented\");\n break;\n case Triple::XCOFF:\n llvm_unreachable(\"XCOFF is not yet implemented\");\n break;\n }\n llvm_unreachable(\"Unimplemented ObjectFormatType\");\n}\n\nstatic const char *getSectionNameForCommandline(const Triple &T) {\n switch (T.getObjectFormat()) {\n case Triple::MachO:\n return \"__LLVM,__cmdline\";\n case Triple::COFF:\n case Triple::ELF:\n case Triple::Wasm:\n case Triple::UnknownObjectFormat:\n return \".llvmcmd\";\n case Triple::GOFF:\n llvm_unreachable(\"GOFF is not yet implemented\");\n break;\n case Triple::XCOFF:\n llvm_unreachable(\"XCOFF is not yet implemented\");\n break;\n }\n llvm_unreachable(\"Unimplemented ObjectFormatType\");\n}\n\nvoid llvm::EmbedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,\n bool EmbedBitcode, bool EmbedCmdline,\n const std::vector &CmdArgs) {\n \/\/ Save llvm.compiler.used and remove it.\n SmallVector UsedArray;\n SmallVector UsedGlobals;\n Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);\n GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);\n for (auto *GV : UsedGlobals) {\n if (GV->getName() != \"llvm.embedded.module\" &&\n GV->getName() != \"llvm.cmdline\")\n UsedArray.push_back(\n ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));\n }\n if (Used)\n Used->eraseFromParent();\n\n \/\/ Embed the bitcode for the llvm module.\n std::string Data;\n ArrayRef ModuleData;\n Triple T(M.getTargetTriple());\n\n if (EmbedBitcode) {\n if (Buf.getBufferSize() == 0 ||\n !isBitcode((const unsigned char *)Buf.getBufferStart(),\n (const unsigned char *)Buf.getBufferEnd())) {\n \/\/ If the input is LLVM Assembly, bitcode is produced by serializing\n \/\/ the module. Use-lists order need to be preserved in this case.\n llvm::raw_string_ostream OS(Data);\n llvm::WriteBitcodeToFile(M, OS, \/* ShouldPreserveUseListOrder *\/ true);\n ModuleData =\n ArrayRef((const uint8_t *)OS.str().data(), OS.str().size());\n } else\n \/\/ If the input is LLVM bitcode, write the input byte stream directly.\n ModuleData = ArrayRef((const uint8_t *)Buf.getBufferStart(),\n Buf.getBufferSize());\n }\n llvm::Constant *ModuleConstant =\n llvm::ConstantDataArray::get(M.getContext(), ModuleData);\n llvm::GlobalVariable *GV = new llvm::GlobalVariable(\n M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,\n ModuleConstant);\n GV->setSection(getSectionNameForBitcode(T));\n \/\/ Set alignment to 1 to prevent padding between two contributions from input\n \/\/ sections after linking.\n GV->setAlignment(Align(1));\n UsedArray.push_back(\n ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));\n if (llvm::GlobalVariable *Old =\n M.getGlobalVariable(\"llvm.embedded.module\", true)) {\n assert(Old->hasOneUse() &&\n \"llvm.embedded.module can only be used once in llvm.compiler.used\");\n GV->takeName(Old);\n Old->eraseFromParent();\n } else {\n GV->setName(\"llvm.embedded.module\");\n }\n\n \/\/ Skip if only bitcode needs to be embedded.\n if (EmbedCmdline) {\n \/\/ Embed command-line options.\n ArrayRef CmdData(const_cast(CmdArgs.data()),\n CmdArgs.size());\n llvm::Constant *CmdConstant =\n llvm::ConstantDataArray::get(M.getContext(), CmdData);\n GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,\n llvm::GlobalValue::PrivateLinkage,\n CmdConstant);\n GV->setSection(getSectionNameForCommandline(T));\n GV->setAlignment(Align(1));\n UsedArray.push_back(\n ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));\n if (llvm::GlobalVariable *Old = M.getGlobalVariable(\"llvm.cmdline\", true)) {\n assert(Old->hasOneUse() &&\n \"llvm.cmdline can only be used once in llvm.compiler.used\");\n GV->takeName(Old);\n Old->eraseFromParent();\n } else {\n GV->setName(\"llvm.cmdline\");\n }\n }\n\n if (UsedArray.empty())\n return;\n\n \/\/ Recreate llvm.compiler.used.\n ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());\n auto *NewUsed = new GlobalVariable(\n M, ATy, false, llvm::GlobalValue::AppendingLinkage,\n llvm::ConstantArray::get(ATy, UsedArray), \"llvm.compiler.used\");\n NewUsed->setSection(\"llvm.metadata\");\n}\n","avg_line_length":38.8564516129,"max_line_length":81,"alphanum_fraction":0.6820752563} {"size":3900,"ext":"hpp","lang":"C++","max_stars_count":81.0,"content":"\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ Licensed under the MIT License.\n\n#ifndef airsim_core_World_hpp\n#define airsim_core_World_hpp\n\n#include \n#include \"common\/Common.hpp\"\n#include \"common\/UpdatableContainer.hpp\"\n#include \"PhysicsEngineBase.hpp\"\n#include \"PhysicsBody.hpp\"\n#include \"common\/common_utils\/ScheduledExecutor.hpp\"\n#include \"common\/ClockFactory.hpp\"\n\nnamespace msr { namespace airlib {\n\nclass World : public UpdatableContainer {\npublic:\n World(std::unique_ptr physics_engine)\n : physics_engine_(std::move(physics_engine))\n { \n World::clear();\n\n if (physics_engine)\n physics_engine_->clear();\n }\n\n \/\/override updatable interface so we can synchronize physics engine\n \/\/*** Start: UpdatableState implementation ***\/\/\n virtual void reset() override\n {\n UpdatableContainer::reset();\n \n if (physics_engine_)\n physics_engine_->reset();\n }\n\n virtual void update() override\n {\n ClockFactory::get()->step();\n\n \/\/first update our objects\n UpdatableContainer::update();\n\n \/\/now update kinematics state\n if (physics_engine_)\n physics_engine_->update();\n }\n\n virtual void reportState(StateReporter& reporter) override\n {\n reporter.writeValue(\"Sleep\", 1.0f \/ executor_.getSleepTimeAvg());\n if (physics_engine_)\n physics_engine_->reportState(reporter);\n\n \/\/call base\n UpdatableContainer::reportState(reporter);\n }\n \/\/*** End: UpdatableState implementation ***\/\/\n\n \/\/override membership modification methods so we can synchronize physics engine\n virtual void clear() override\n { \n if (physics_engine_)\n physics_engine_->clear();\n UpdatableContainer::clear();\n }\n\n virtual void insert(UpdatableObject* member) override\n { \n if (physics_engine_ && member->getPhysicsBody() != nullptr)\n physics_engine_->insert(static_cast(member->getPhysicsBody()));\n\n UpdatableContainer::insert(member);\n }\n\n virtual void erase_remove(UpdatableObject* member) override\n { \n if (physics_engine_ && member->getPhysicsBody() != nullptr)\n physics_engine_->erase_remove(static_cast(\n member->getPhysicsBody()));\n\n UpdatableContainer::erase_remove(member);\n }\n\n \/\/async updater thread\n void startAsyncUpdator(uint64_t period)\n {\n \/\/TODO: probably we shouldn't be passing around fixed period\n executor_.initialize(std::bind(&World::worldUpdatorAsync, this, std::placeholders::_1), period);\n executor_.start();\n }\n void stopAsyncUpdator()\n {\n executor_.stop();\n }\n void lock()\n {\n executor_.lock();\n }\n void unlock()\n {\n executor_.unlock();\n }\n\n virtual ~World()\n {\n executor_.stop();\n }\n\n void pause(bool is_paused)\n {\n executor_.pause(is_paused);\n }\n\n bool isPaused() const\n {\n return executor_.isPaused();\n }\n\n void continueForTime(double seconds)\n {\n executor_.continueForTime(seconds);\n }\n\nprivate:\n bool worldUpdatorAsync(uint64_t dt_nanos)\n {\n unused(dt_nanos);\n\n try {\n update();\n }\n catch(const std::exception& ex) {\n \/\/Utils::DebugBreak();\n Utils::log(Utils::stringf(\"Exception occurred while updating world: %s\", ex.what()), Utils::kLogLevelError);\n }\n catch(...) {\n \/\/Utils::DebugBreak();\n Utils::log(\"Exception occurred while updating world\", Utils::kLogLevelError);\n }\n\n return true;\n }\n\nprivate:\n std::unique_ptr physics_engine_ = nullptr;\n common_utils::ScheduledExecutor executor_;\n};\n\n}} \/\/namespace\n#endif\n","avg_line_length":25.4901960784,"max_line_length":120,"alphanum_fraction":0.6294871795} {"size":4333,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \"bitcoinunits.h\"\n\n#include \n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList BitcoinUnits::availableUnits()\n{\n QList unitlist;\n unitlist.append(BTC);\n unitlist.append(mBTC);\n unitlist.append(uBTC);\n return unitlist;\n}\n\nbool BitcoinUnits::valid(int unit)\n{\n switch(unit)\n {\n case BTC:\n case mBTC:\n case uBTC:\n return true;\n default:\n return false;\n }\n}\n\nQString BitcoinUnits::name(int unit)\n{\n switch(unit)\n {\n case BTC: return QString(\"GEO\");\n case mBTC: return QString(\"mGEO\");\n case uBTC: return QString::fromUtf8(\"\u03bcGEO\");\n default: return QString(\"???\");\n }\n}\n\nQString BitcoinUnits::description(int unit)\n{\n switch(unit)\n {\n case BTC: return QString(\"CoinTer\");\n case mBTC: return QString(\"milliCoinTer (1 \/ 1,000)\");\n case uBTC: return QString(\"microCoinTer (1 \/ 1,000,000)\");\n default: return QString(\"???\");\n }\n}\n\/\/a single unit (.00000001) of CoinTer is called a \"wander.\"\nqint64 BitcoinUnits::factor(int unit)\n{\n switch(unit)\n {\n case BTC: return 100000000;\n case mBTC: return 100000;\n case uBTC: return 100;\n default: return 100000000;\n }\n}\n\nint BitcoinUnits::amountDigits(int unit)\n{\n switch(unit)\n {\n case BTC: return 8; \/\/ 21,000,000 (# digits, without commas)\n case mBTC: return 11; \/\/ 21,000,000,000\n case uBTC: return 14; \/\/ 21,000,000,000,000\n default: return 0;\n }\n}\n\nint BitcoinUnits::decimals(int unit)\n{\n switch(unit)\n {\n case BTC: return 8;\n case mBTC: return 5;\n case uBTC: return 2;\n default: return 0;\n }\n}\n\nQString BitcoinUnits::format(int unit, qint64 n, bool fPlus)\n{\n \/\/ Note: not using straight sprintf here because we do NOT want\n \/\/ localized number formatting.\n if(!valid(unit))\n return QString(); \/\/ Refuse to format invalid unit\n qint64 coin = factor(unit);\n int num_decimals = decimals(unit);\n qint64 n_abs = (n > 0 ? n : -n);\n qint64 quotient = n_abs \/ coin;\n qint64 remainder = n_abs % coin;\n QString quotient_str = QString::number(quotient);\n QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n \/\/ Right-trim excess 0's after the decimal point\n int nTrim = 0;\n for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)\n ++nTrim;\n remainder_str.chop(nTrim);\n\n if (n < 0)\n quotient_str.insert(0, '-');\n else if (fPlus && n > 0)\n quotient_str.insert(0, '+');\n return quotient_str + QString(\".\") + remainder_str;\n}\n\nQString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)\n{\n return format(unit, amount, plussign) + QString(\" \") + name(unit);\n}\n\nbool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)\n{\n if(!valid(unit) || value.isEmpty())\n return false; \/\/ Refuse to parse invalid unit or empty string\n int num_decimals = decimals(unit);\n QStringList parts = value.split(\".\");\n\n if(parts.size() > 2)\n {\n return false; \/\/ More than one dot\n }\n QString whole = parts[0];\n QString decimals;\n\n if(parts.size() > 1)\n {\n decimals = parts[1];\n }\n if(decimals.size() > num_decimals)\n {\n return false; \/\/ Exceeds max precision\n }\n bool ok = false;\n QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n if(str.size() > 18)\n {\n return false; \/\/ Longer numbers will exceed 63 bits\n }\n qint64 retvalue = str.toLongLong(&ok);\n if(val_out)\n {\n *val_out = retvalue;\n }\n return ok;\n}\n\nint BitcoinUnits::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return unitlist.size();\n}\n\nQVariant BitcoinUnits::data(const QModelIndex &index, int role) const\n{\n int row = index.row();\n if(row >= 0 && row < unitlist.size())\n {\n Unit unit = unitlist.at(row);\n switch(role)\n {\n case Qt::EditRole:\n case Qt::DisplayRole:\n return QVariant(name(unit));\n case Qt::ToolTipRole:\n return QVariant(description(unit));\n case UnitRole:\n return QVariant(static_cast(unit));\n }\n }\n return QVariant();\n}\n","avg_line_length":23.8076923077,"max_line_length":89,"alphanum_fraction":0.6145857374} {"size":2733,"ext":"hpp","lang":"C++","max_stars_count":9182.0,"content":"\/**\n * \\file\n * \\author T. Canham\n * \\brief Component that stores telemetry channel values\n *\n * \\copyright\n * Copyright 2009-2015, by the California Institute of Technology.\n * ALL RIGHTS RESERVED. United States Government Sponsorship\n * acknowledged.\n *

\n *\/\n\n#ifndef TELEMCHANIMPL_HPP_\n#define TELEMCHANIMPL_HPP_\n\n#include \n#include \n#include \n#include \n\nnamespace Svc {\n\n class TlmChanImpl: public TlmChanComponentBase {\n public:\n friend class TlmChanImplTester;\n TlmChanImpl(const char* compName);\n virtual ~TlmChanImpl();\n void init(\n NATIVE_INT_TYPE queueDepth, \/*!< The queue depth*\/\n NATIVE_INT_TYPE instance \/*!< The instance number*\/\n );\n PROTECTED:\n\n \/\/ can be overridden for alternate algorithms\n virtual NATIVE_UINT_TYPE doHash(FwChanIdType id);\n\n PRIVATE:\n\n \/\/ Port functions\n void TlmRecv_handler(NATIVE_INT_TYPE portNum, FwChanIdType id, Fw::Time &timeTag, Fw::TlmBuffer &val);\n void TlmGet_handler(NATIVE_INT_TYPE portNum, FwChanIdType id, Fw::Time &timeTag, Fw::TlmBuffer &val);\n void Run_handler(NATIVE_INT_TYPE portNum, NATIVE_UINT_TYPE context);\n \/\/! Handler implementation for pingIn\n \/\/!\n void pingIn_handler(\n const NATIVE_INT_TYPE portNum, \/*!< The port number*\/\n U32 key \/*!< Value to return to pinger*\/\n );\n\n typedef struct tlmEntry {\n FwChanIdType id; \/\/!< telemetry id stored in slot\n bool updated; \/\/!< set whenever a value has been written. Used to skip if writing out values for downlinking\n Fw::Time lastUpdate; \/\/!< last updated time\n Fw::TlmBuffer buffer; \/\/!< buffer to store serialized telemetry\n tlmEntry* next; \/\/!< pointer to next bucket in table\n bool used; \/\/!< if entry has been used\n NATIVE_UINT_TYPE bucketNo; \/\/!< for testing\n } TlmEntry;\n\n struct TlmSet {\n TlmEntry* slots[TLMCHAN_NUM_TLM_HASH_SLOTS]; \/\/!< set of hash slots in hash table\n TlmEntry buckets[TLMCHAN_HASH_BUCKETS]; \/\/!< set of buckets used in hash table\n NATIVE_INT_TYPE free; \/\/!< next free bucket\n } m_tlmEntries[2];\n\n U32 m_activeBuffer; \/\/ !< which buffer is active for storing telemetry\n\n \/\/ work variables\n Fw::ComBuffer m_comBuffer;\n Fw::TlmPacket m_tlmPacket;\n\n };\n\n}\n\n#endif \/* TELEMCHANIMPL_HPP_ *\/\n","avg_line_length":35.4935064935,"max_line_length":124,"alphanum_fraction":0.6059275521} {"size":3724,"ext":"cpp","lang":"C++","max_stars_count":1.0,"content":"\/\/ Copyright (c) 2014-2017 The Bitcoin developers\n\/\/ Copyright (c) 2017-2020 The PIVX developers\n\/\/ Copyright (c) 2021 The VOLTNOTE developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"timedata.h\"\n\n#include \"chainparams.h\"\n#include \"guiinterface.h\"\n#include \"netaddress.h\"\n#include \"sync.h\"\n#include \"util.h\"\n#include \"warnings.h\"\n\n\nstatic RecursiveMutex cs_nTimeOffset;\nstatic int64_t nTimeOffset = 0;\n\n\/**\n * \"Never go to sea with two chronometers; take one or three.\"\n * Our three time sources are:\n * - System clock\n * - Median of other nodes clocks\n * - The user (asking the user to fix the system clock if the first two disagree)\n *\/\nint64_t GetTimeOffset()\n{\n LOCK(cs_nTimeOffset);\n return nTimeOffset;\n}\n\nint64_t GetAdjustedTime()\n{\n return GetTime() + GetTimeOffset();\n}\n\n#define BITCOIN_TIMEDATA_MAX_SAMPLES 200\n\nvoid AddTimeData(const CNetAddr& ip, int64_t nOffsetSample, int nOffsetLimit)\n{\n LOCK(cs_nTimeOffset);\n \/\/ Ignore duplicates (Except on regtest where all nodes have the same ip)\n static std::set setKnown;\n if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)\n return;\n if (!Params().IsRegTestNet() && !setKnown.insert(ip).second)\n return;\n\n \/\/ Add data\n static CMedianFilter vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);\n vTimeOffsets.input(nOffsetSample);\n LogPrintf(\"Added time data, samples %d, offset %+d (%+d minutes)\\n\", vTimeOffsets.size(), nOffsetSample, nOffsetSample \/ 60);\n\n \/\/ There is a known issue here (see issue #4521):\n \/\/\n \/\/ - The structure vTimeOffsets contains up to 200 elements, after which\n \/\/ any new element added to it will not increase its size, replacing the\n \/\/ oldest element.\n \/\/\n \/\/ - The condition to update nTimeOffset includes checking whether the\n \/\/ number of elements in vTimeOffsets is odd, which will never happen after\n \/\/ there are 200 elements.\n \/\/\n \/\/ But in this case the 'bug' is protective against some attacks, and may\n \/\/ actually explain why we've never seen attacks which manipulate the\n \/\/ clock offset.\n \/\/\n \/\/ So we should hold off on fixing this and clean it up as part of\n \/\/ a timing cleanup that strengthens it in a number of other ways.\n \/\/\n if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) {\n int64_t nMedian = vTimeOffsets.median();\n std::vector vSorted = vTimeOffsets.sorted();\n \/\/ Only let other nodes change our time by so much\n if (abs64(nMedian) < nOffsetLimit) {\n nTimeOffset = nMedian;\n SetMiscWarning(\"\");\n } else {\n nTimeOffset = (nMedian > 0 ? 1 : -1) * nOffsetLimit;\n std::string strMessage = _(\"Warning: Please check that your computer's date and time are correct! If your clock is wrong VOLTNOTE will not work properly.\");\n SetMiscWarning(strMessage);\n LogPrintf(\"*** %s\\n\", strMessage);\n uiInterface.ThreadSafeMessageBox(strMessage, \"\", CClientUIInterface::MSG_ERROR);\n }\n if (!gArgs.GetBoolArg(\"-shrinkdebugfile\", g_logger->DefaultShrinkDebugFile())) {\n for (int64_t n : vSorted)\n LogPrintf(\"%+d \", n);\n LogPrintf(\"| \");\n }\n LogPrintf(\"nTimeOffset = %+d\\n\", nTimeOffset);\n }\n}\n\n\/\/ Time Protocol V2\n\/\/ Timestamp for time protocol V2: slot duration 15 seconds\nint64_t GetTimeSlot(const int64_t nTime)\n{\n const int slotLen = Params().GetConsensus().nTimeSlotLength;\n return (nTime \/ slotLen) * slotLen;\n}\n\nint64_t GetCurrentTimeSlot()\n{\n return GetTimeSlot(GetAdjustedTime());\n}\n","avg_line_length":34.8037383178,"max_line_length":168,"alphanum_fraction":0.6721267454} {"size":6013,"ext":"cc","lang":"C++","max_stars_count":1.0,"content":"\/\/ Copyright 2019 The Fuchsia Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"src\/developer\/debug\/zxdb\/expr\/expr_token_type.h\"\n\n#include \n\n#include \n\n#include \"src\/developer\/debug\/zxdb\/expr\/expr_language.h\"\n\nnamespace zxdb {\n\nnamespace {\n\n\/\/ A constexpr version of isalnum.\nconstexpr bool IsAlnum(char c) {\n return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');\n}\n\nconstexpr bool StringIsAlphanum(std::string_view str) {\n for (char c : str) {\n if (!IsAlnum(c))\n return false;\n }\n return true;\n}\n\n} \/\/ namespace\n\n\/\/ Must come before the tables below.\nconstexpr ExprTokenRecord::ExprTokenRecord(ExprTokenType t, unsigned langs,\n std::string_view static_val)\n : type(t),\n static_value(static_val),\n is_alphanum(StringIsAlphanum(static_val)),\n languages(langs) {}\n\nnamespace {\n\nconstexpr unsigned kLangAll =\n static_cast(ExprLanguage::kC) | static_cast(ExprLanguage::kRust);\nconstexpr unsigned kLangC = static_cast(ExprLanguage::kC);\nconstexpr unsigned kLangRust = static_cast(ExprLanguage::kRust);\n\n\/\/ Note that we allow a number of things like \"sizeof\" in Rust as well because there are no good\n\/\/ alternatives and these constructs can be useful. We may consider replacing them with a more\n\/\/ Rust-like construct in the future.\nconstexpr ExprTokenRecord kRecords[kNumExprTokenTypes] = {\n \/\/ clang-format off\n {ExprTokenType::kInvalid, 0},\n {ExprTokenType::kName, kLangAll},\n {ExprTokenType::kSpecialName, kLangAll},\n {ExprTokenType::kInteger, kLangAll},\n {ExprTokenType::kFloat, kLangAll},\n {ExprTokenType::kStringLiteral, kLangAll},\n {ExprTokenType::kEquals, kLangAll, \"=\"},\n {ExprTokenType::kEquality, kLangAll, \"==\"},\n {ExprTokenType::kInequality, kLangAll, \"!=\"},\n {ExprTokenType::kLessEqual, kLangAll, \"<=\"},\n {ExprTokenType::kGreaterEqual, kLangAll, \">=\"},\n {ExprTokenType::kSpaceship, kLangAll, \"<=>\"},\n {ExprTokenType::kDot, kLangAll, \".\"},\n {ExprTokenType::kDotStar, kLangC, \".*\"},\n {ExprTokenType::kComma, kLangAll, \",\"},\n {ExprTokenType::kSemicolon, kLangAll, \";\"},\n {ExprTokenType::kStar, kLangAll, \"*\"},\n {ExprTokenType::kAmpersand, kLangAll, \"&\"},\n {ExprTokenType::kDoubleAnd, kLangAll, \"&&\"},\n {ExprTokenType::kBitwiseOr, kLangAll, \"|\"},\n {ExprTokenType::kLogicalOr, kLangAll, \"||\"},\n {ExprTokenType::kArrow, kLangAll, \"->\"},\n {ExprTokenType::kArrowStar, kLangC, \"->*\"},\n {ExprTokenType::kLeftSquare, kLangAll, \"[\"},\n {ExprTokenType::kRightSquare, kLangAll, \"]\"},\n {ExprTokenType::kLeftParen, kLangAll, \"(\"},\n {ExprTokenType::kRightParen, kLangAll, \")\"},\n {ExprTokenType::kLeftBracket, kLangAll, \"{\"},\n {ExprTokenType::kRightBracket, kLangAll, \"}\"},\n {ExprTokenType::kLess, kLangAll, \"<\"},\n {ExprTokenType::kGreater, kLangAll, \">\"},\n {ExprTokenType::kMinus, kLangAll, \"-\"},\n {ExprTokenType::kMinusMinus, kLangC, \"--\"},\n {ExprTokenType::kBang, kLangAll, \"!\"},\n {ExprTokenType::kPlus, kLangAll, \"+\"},\n {ExprTokenType::kPlusPlus, kLangC, \"++\"},\n {ExprTokenType::kSlash, kLangAll, \"\/\"},\n {ExprTokenType::kCaret, kLangAll, \"^\"},\n {ExprTokenType::kPercent, kLangAll, \"%\"},\n {ExprTokenType::kQuestion, kLangAll, \"?\"},\n {ExprTokenType::kTilde, kLangC, \"~\"},\n {ExprTokenType::kColon, kLangAll, \":\"},\n {ExprTokenType::kColonColon, kLangAll, \"::\"},\n {ExprTokenType::kPlusEquals, kLangC, \"+=\"},\n {ExprTokenType::kMinusEquals, kLangC, \"-=\"},\n {ExprTokenType::kStarEquals, kLangC, \"*=\"},\n {ExprTokenType::kSlashEquals, kLangC, \"\/=\"},\n {ExprTokenType::kPercentEquals, kLangC, \"%=\"},\n {ExprTokenType::kCaretEquals, kLangC, \"^=\"},\n {ExprTokenType::kAndEquals, kLangC, \"&=\"},\n {ExprTokenType::kOrEquals, kLangC, \"|=\"},\n {ExprTokenType::kShiftLeft, kLangAll, \"<<\"},\n {ExprTokenType::kShiftLeftEquals, kLangC, \"<<=\"},\n {ExprTokenType::kShiftRight, kLangAll, \">>\"},\n {ExprTokenType::kShiftRightEquals, kLangC, \">>=\"},\n {ExprTokenType::kTrue, kLangAll, \"true\"},\n {ExprTokenType::kFalse, kLangAll, \"false\"},\n {ExprTokenType::kConst, kLangAll, \"const\"},\n {ExprTokenType::kMut, kLangRust, \"mut\"},\n {ExprTokenType::kVolatile, kLangC, \"volatile\"},\n {ExprTokenType::kRestrict, kLangC, \"restrict\"},\n {ExprTokenType::kReinterpretCast, kLangC, \"reinterpret_cast\"},\n {ExprTokenType::kStaticCast, kLangC, \"static_cast\"},\n {ExprTokenType::kSizeof, kLangAll, \"sizeof\"},\n {ExprTokenType::kAs, kLangRust, \"as\"},\n {ExprTokenType::kIf, kLangAll, \"if\"},\n {ExprTokenType::kElse, kLangAll, \"else\"},\n {ExprTokenType::kOperator, kLangC, \"operator\"},\n {ExprTokenType::kNew, kLangC, \"new\"},\n {ExprTokenType::kDelete, kLangC, \"delete\"},\n \/\/ clang-format on\n};\n\n} \/\/ namespace\n\nconst ExprTokenRecord& RecordForTokenType(ExprTokenType type) {\n static_assert(std::size(kRecords) == static_cast(ExprTokenType::kNumTypes),\n \"kRecords needs updating to match ExprTokenType\");\n\n \/\/ Checks that this record is in the right place.\n FX_DCHECK(kRecords[static_cast(type)].type == type);\n\n return kRecords[static_cast(type)];\n}\n\n} \/\/ namespace zxdb\n","avg_line_length":43.5724637681,"max_line_length":96,"alphanum_fraction":0.5905538001} {"size":3847,"ext":"cpp","lang":"C++","max_stars_count":3.0,"content":"#include \n#include \n#include \"TriggerObserver.hpp\"\n\n#ifdef USINGMEMTRACK\n#include \n#endif\n\nnamespace Physics {\n TriggerObserver::TriggerObserver(btCollisionObject& body)\n : btCollisionWorld::ContactResultCallback(), rigidBody(body) {\n\n }\n\n btCollisionObject* TriggerObserver::GetBulletCollisionObject() {\n return &rigidBody;\n }\n\n TriggerObserver::IntersectionPhase TriggerObserver::GetPhase() const {\n return phase;\n }\n\n void TriggerObserver::PostIntersectionTest() {\n if (didCallback) {\n \/\/ Intersection happened; update phase accordingly.\n switch (phase) {\n case IntersectionPhase::Enter: {\n phase = IntersectionPhase::Retained;\n break;\n }\n case IntersectionPhase::Leave: {\n phase = IntersectionPhase::Enter;\n break;\n }\n case IntersectionPhase::None: {\n phase = IntersectionPhase::Enter;\n break;\n }\n default: {\n assert(phase == IntersectionPhase::Retained);\n }\n }\n } else {\n \/\/ No intersection happened; update phase accordingly.\n switch (phase) {\n case IntersectionPhase::Enter: {\n phase = IntersectionPhase::Leave;\n break;\n }\n case IntersectionPhase::Retained: {\n phase = IntersectionPhase::Leave;\n break;\n }\n case IntersectionPhase::Leave: {\n phase = IntersectionPhase::None;\n break;\n }\n default: {\n assert(phase == IntersectionPhase::None);\n }\n }\n }\n\n \/\/ Call event handler accordingly.\n switch (phase) {\n case IntersectionPhase::Enter: {\n if (enterHandler) {\n enterHandler();\n }\n break;\n }\n case IntersectionPhase::Retained: {\n if (retainHandler) {\n retainHandler();\n }\n break;\n }\n case IntersectionPhase::Leave: {\n if (leaveHandler) {\n leaveHandler();\n }\n break;\n }\n default: {\n assert(phase == IntersectionPhase::None);\n }\n }\n\n \/\/ Prepare for next invocation.\n didCallback = false;\n }\n\n void TriggerObserver::OnEnter(const std::function& handler) {\n enterHandler = handler;\n }\n\n void TriggerObserver::ForgetEnter() {\n enterHandler = nullptr;\n }\n\n void TriggerObserver::OnRetain(const std::function& handler) {\n retainHandler = handler;\n }\n\n void TriggerObserver::ForgetRetain() {\n retainHandler = nullptr;\n }\n\n void TriggerObserver::OnLeave(const std::function& handler) {\n leaveHandler = handler;\n }\n\n void TriggerObserver::ForgetLeave() {\n leaveHandler = nullptr;\n }\n\n \/\/ Called with each contact for our own processing. This is where we can\n \/\/ provide custom intersection handling.\n btScalar TriggerObserver::addSingleResult(btManifoldPoint& cp,\n const btCollisionObjectWrapper* colObj0, int partId0, int index0,\n const btCollisionObjectWrapper* colObj1, int partId1, int index1) {\n\n assert(colObj0->getCollisionObject() == &rigidBody || colObj1->getCollisionObject() == &rigidBody);\n didCallback = true;\n\n return 0; \/\/ Was a planned purpose, but is not used.\n }\n}\n","avg_line_length":29.8217054264,"max_line_length":107,"alphanum_fraction":0.5235248245} {"size":1272,"ext":"cpp","lang":"C++","max_stars_count":3.0,"content":"#include \"ResampleWork.h\"\n#include \"QUtils.h\"\n\n#include \n\nResampleWork::ResampleWork(QObject *parent) : BaseWork(parent) {\n m_skipExist = false;\n}\n\nResampleWork::~ResampleWork() {\n}\n\nvoid ResampleWork::startCore() {\n m_process->setProgram(m_resampler);\n m_process->setWorkingDirectory(m_workingDir);\n m_process->setArguments(m_args.fullArguments());\n\n emit started();\n\n if (!isFileExist(m_resampler)) {\n handleProcessFinished(0, QProcess::CrashExit);\n } else if (!m_skipExist || !isFileExist(m_args.outFile())) {\n m_process->start();\n } else {\n handleProcessFinished(0, QProcess::NormalExit);\n }\n}\n\nQString ResampleWork::workingDir() const {\n return m_workingDir;\n}\n\nvoid ResampleWork::setWorkingDir(const QString &workingDir) {\n m_workingDir = workingDir;\n}\n\nQString ResampleWork::resampler() const {\n return m_resampler;\n}\n\nvoid ResampleWork::setResampler(const QString &resampler) {\n m_resampler = resampler;\n}\n\nResamplerArgs ResampleWork::args() const {\n return m_args;\n}\n\nvoid ResampleWork::setArgs(const ResamplerArgs &args) {\n m_args = args;\n}\n\nbool ResampleWork::skipExist() const {\n return m_skipExist;\n}\n\nvoid ResampleWork::setSkipExist(bool skipExist) {\n m_skipExist = skipExist;\n}\n","avg_line_length":21.2,"max_line_length":64,"alphanum_fraction":0.7059748428} {"size":3923,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"editaddressdialog.h\"\n#include \"ui_editaddressdialog.h\"\n\n#include \"addresstablemodel.h\"\n#include \"guiutil.h\"\n\n#include \n#include \n\nEditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)\n{\n ui->setupUi(this);\n\n GUIUtil::setupAddressWidget(ui->addressEdit, this);\n\n switch(mode)\n {\n case NewReceivingAddress:\n setWindowTitle(tr(\"New receiving address\"));\n ui->addressEdit->setEnabled(false);\n break;\n case NewSendingAddress:\n setWindowTitle(tr(\"New sending address\"));\n break;\n case EditReceivingAddress:\n setWindowTitle(tr(\"Edit receiving address\"));\n ui->addressEdit->setEnabled(false);\n break;\n case EditSendingAddress:\n setWindowTitle(tr(\"Edit sending address\"));\n break;\n }\n\n mapper = new QDataWidgetMapper(this);\n mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n}\n\nEditAddressDialog::~EditAddressDialog()\n{\n delete ui;\n}\n\nvoid EditAddressDialog::setModel(AddressTableModel *model)\n{\n this->model = model;\n if(!model)\n return;\n\n mapper->setModel(model);\n mapper->addMapping(ui->labelEdit, AddressTableModel::Label);\n mapper->addMapping(ui->addressEdit, AddressTableModel::Address);\n}\n\nvoid EditAddressDialog::loadRow(int row)\n{\n mapper->setCurrentIndex(row);\n}\n\nbool EditAddressDialog::saveCurrentRow()\n{\n if(!model)\n return false;\n\n switch(mode)\n {\n case NewReceivingAddress:\n case NewSendingAddress:\n address = model->addRow(\n mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,\n ui->labelEdit->text(),\n ui->addressEdit->text());\n break;\n case EditReceivingAddress:\n case EditSendingAddress:\n if(mapper->submit())\n {\n address = ui->addressEdit->text();\n }\n break;\n }\n return !address.isEmpty();\n}\n\nvoid EditAddressDialog::accept()\n{\n if(!model)\n return;\n\n if(!saveCurrentRow())\n {\n switch(model->getEditStatus())\n {\n case AddressTableModel::OK:\n \/\/ Failed with unknown reason. Just reject.\n break;\n case AddressTableModel::NO_CHANGES:\n \/\/ No changes were made during edit operation. Just reject.\n break;\n case AddressTableModel::INVALID_ADDRESS:\n QMessageBox::warning(this, windowTitle(),\n tr(\"The entered address \\\"%1\\\" is not a valid Rcoin address.\").arg(ui->addressEdit->text()),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::DUPLICATE_ADDRESS:\n QMessageBox::warning(this, windowTitle(),\n tr(\"The entered address \\\"%1\\\" is already in the address book.\").arg(ui->addressEdit->text()),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::WALLET_UNLOCK_FAILURE:\n QMessageBox::critical(this, windowTitle(),\n tr(\"Could not unlock wallet.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::KEY_GENERATION_FAILURE:\n QMessageBox::critical(this, windowTitle(),\n tr(\"New key generation failed.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n\n }\n return;\n }\n QDialog::accept();\n}\n\nQString EditAddressDialog::getAddress() const\n{\n return address;\n}\n\nvoid EditAddressDialog::setAddress(const QString &address)\n{\n this->address = address;\n ui->addressEdit->setText(address);\n}\n","avg_line_length":27.6267605634,"max_line_length":110,"alphanum_fraction":0.6278358399} {"size":19810,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Copyright (c) 2013 The NovaCoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"txdb.h\"\n#include \"miner.h\"\n#include \"kernel.h\"\n\n#include \n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ BitcoinMiner\n\/\/\n\nextern unsigned int nMinerSleep;\n\nint static FormatHashBlocks(void* pbuffer, unsigned int len)\n{\n unsigned char* pdata = (unsigned char*)pbuffer;\n unsigned int blocks = 1 + ((len + 8) \/ 64);\n unsigned char* pend = pdata + 64 * blocks;\n memset(pdata + len, 0, 64 * blocks - len);\n pdata[len] = 0x80;\n unsigned int bits = len * 8;\n pend[-1] = (bits >> 0) & 0xff;\n pend[-2] = (bits >> 8) & 0xff;\n pend[-3] = (bits >> 16) & 0xff;\n pend[-4] = (bits >> 24) & 0xff;\n return blocks;\n}\n\nstatic const unsigned int pSHA256InitState[8] =\n{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};\n\nvoid SHA256Transform(void* pstate, void* pinput, const void* pinit)\n{\n SHA256_CTX ctx;\n unsigned char data[64];\n\n SHA256_Init(&ctx);\n\n for (int i = 0; i < 16; i++)\n ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);\n\n for (int i = 0; i < 8; i++)\n ctx.h[i] = ((uint32_t*)pinit)[i];\n\n SHA256_Update(&ctx, data, sizeof(data));\n for (int i = 0; i < 8; i++)\n ((uint32_t*)pstate)[i] = ctx.h[i];\n}\n\n\/\/ Some explaining would be appreciated\nclass COrphan\n{\npublic:\n CTransaction* ptx;\n set setDependsOn;\n double dPriority;\n double dFeePerKb;\n\n COrphan(CTransaction* ptxIn)\n {\n ptx = ptxIn;\n dPriority = dFeePerKb = 0;\n }\n};\n\n\nuint64_t nLastBlockTx = 0;\nuint64_t nLastBlockSize = 0;\nint64_t nLastCoinStakeSearchInterval = 0;\n \n\/\/ We want to sort transactions by priority and fee, so:\ntypedef boost::tuple TxPriority;\nclass TxPriorityCompare\n{\n bool byFee;\npublic:\n TxPriorityCompare(bool _byFee) : byFee(_byFee) { }\n bool operator()(const TxPriority& a, const TxPriority& b)\n {\n if (byFee)\n {\n if (a.get<1>() == b.get<1>())\n return a.get<0>() < b.get<0>();\n return a.get<1>() < b.get<1>();\n }\n else\n {\n if (a.get<0>() == b.get<0>())\n return a.get<1>() < b.get<1>();\n return a.get<0>() < b.get<0>();\n }\n }\n};\n\n\/\/ CreateNewBlock: create new block (without proof-of-work\/proof-of-stake)\nCBlock* CreateNewBlock(CReserveKey& reservekey, bool fProofOfStake, int64_t* pFees)\n{\n \/\/ Create new block\n std::unique_ptr pblock(new CBlock());\n if (!pblock.get())\n return NULL;\n\n CBlockIndex* pindexPrev = pindexBest;\n int nHeight = pindexPrev->nHeight + 1;\n\n \/\/ Create coinbase tx\n CTransaction txNew;\n txNew.vin.resize(1);\n txNew.vin[0].prevout.SetNull();\n txNew.vout.resize(1);\n\n if (!fProofOfStake)\n {\n CPubKey pubkey;\n if (!reservekey.GetReservedKey(pubkey))\n return NULL;\n txNew.vout[0].scriptPubKey.SetDestination(pubkey.GetID());\n }\n else\n {\n \/\/ Height first in coinbase required for block.version=2\n txNew.vin[0].scriptSig = (CScript() << nHeight) + COINBASE_FLAGS;\n assert(txNew.vin[0].scriptSig.size() <= 100);\n\n txNew.vout[0].SetEmpty();\n }\n\n \/\/ Add our coinbase tx as first transaction\n pblock->vtx.push_back(txNew);\n\n \/\/ Largest block you're willing to create:\n unsigned int nBlockMaxSize = GetArg(\"-blockmaxsize\", MAX_BLOCK_SIZE_GEN\/2);\n \/\/ Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:\n nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));\n\n \/\/ How much of the block should be dedicated to high-priority transactions,\n \/\/ included regardless of the fees they pay\n unsigned int nBlockPrioritySize = GetArg(\"-blockprioritysize\", 27000);\n nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);\n\n \/\/ Minimum block size you want to create; block will be filled with free transactions\n \/\/ until there are no more or the block reaches this size:\n unsigned int nBlockMinSize = GetArg(\"-blockminsize\", 0);\n nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);\n\n \/\/ Fee-per-kilobyte amount considered the same as \"free\"\n \/\/ Be careful setting this: if you set it to zero then\n \/\/ a transaction spammer can cheaply fill blocks using\n \/\/ 1-satoshi-fee transactions. It should be set above the real\n \/\/ cost to you of processing a transaction.\n int64_t nMinTxFee = MIN_TX_FEE;\n if (mapArgs.count(\"-mintxfee\"))\n ParseMoney(mapArgs[\"-mintxfee\"], nMinTxFee);\n\n pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);\n\n \/\/ Collect memory pool transactions into the block\n int64_t nFees = 0;\n {\n LOCK2(cs_main, mempool.cs);\n CTxDB txdb(\"r\");\n\n \/\/ Priority order to process transactions\n list vOrphan; \/\/ list memory doesn't move\n map > mapDependers;\n\n \/\/ This vector will be sorted into a priority queue:\n vector vecPriority;\n vecPriority.reserve(mempool.mapTx.size());\n for (map::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)\n {\n CTransaction& tx = (*mi).second;\n if (tx.IsCoinBase() || tx.IsCoinStake() || !IsFinalTx(tx, nHeight))\n continue;\n\n COrphan* porphan = NULL;\n double dPriority = 0;\n int64_t nTotalIn = 0;\n bool fMissingInputs = false;\n BOOST_FOREACH(const CTxIn& txin, tx.vin)\n {\n \/\/ Read prev transaction\n CTransaction txPrev;\n CTxIndex txindex;\n if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))\n {\n \/\/ This should never happen; all transactions in the memory\n \/\/ pool should connect to either transactions in the chain\n \/\/ or other transactions in the memory pool.\n if (!mempool.mapTx.count(txin.prevout.hash))\n {\n LogPrintf(\"ERROR: mempool transaction missing input\\n\");\n if (fDebug) assert(\"mempool transaction missing input\" == 0);\n fMissingInputs = true;\n if (porphan)\n vOrphan.pop_back();\n break;\n }\n\n \/\/ Has to wait for dependencies\n if (!porphan)\n {\n \/\/ Use list for automatic deletion\n vOrphan.push_back(COrphan(&tx));\n porphan = &vOrphan.back();\n }\n mapDependers[txin.prevout.hash].push_back(porphan);\n porphan->setDependsOn.insert(txin.prevout.hash);\n nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;\n continue;\n }\n int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;\n nTotalIn += nValueIn;\n\n int nConf = txindex.GetDepthInMainChain();\n dPriority += (double)nValueIn * nConf;\n }\n if (fMissingInputs) continue;\n\n \/\/ Priority is sum(valuein * age) \/ txsize\n unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n dPriority \/= nTxSize;\n\n \/\/ This is a more accurate fee-per-kilobyte than is used by the client code, because the\n \/\/ client code rounds up the size to the nearest 1K. That's good, because it gives an\n \/\/ incentive to create smaller transactions.\n double dFeePerKb = double(nTotalIn-tx.GetValueOut()) \/ (double(nTxSize)\/1000.0);\n\n if (porphan)\n {\n porphan->dPriority = dPriority;\n porphan->dFeePerKb = dFeePerKb;\n }\n else\n vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));\n }\n\n \/\/ Collect transactions into block\n map mapTestPool;\n uint64_t nBlockSize = 1000;\n uint64_t nBlockTx = 0;\n int nBlockSigOps = 100;\n bool fSortedByFee = (nBlockPrioritySize <= 0);\n\n TxPriorityCompare comparer(fSortedByFee);\n std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);\n\n while (!vecPriority.empty())\n {\n \/\/ Take highest priority transaction off the priority queue:\n double dPriority = vecPriority.front().get<0>();\n double dFeePerKb = vecPriority.front().get<1>();\n CTransaction& tx = *(vecPriority.front().get<2>());\n\n std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);\n vecPriority.pop_back();\n\n \/\/ Size limits\n unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);\n if (nBlockSize + nTxSize >= nBlockMaxSize)\n continue;\n\n \/\/ Legacy limits on sigOps:\n unsigned int nTxSigOps = GetLegacySigOpCount(tx);\n if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)\n continue;\n\n \/\/ Timestamp limit\n if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))\n continue;\n\n \/\/ Transaction fee\n int64_t nMinFee = GetMinFee(tx, nBlockSize, GMF_BLOCK);\n\n \/\/ Skip free transactions if we're past the minimum block size:\n if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))\n continue;\n\n \/\/ Prioritize by fee once past the priority size or we run out of high-priority\n \/\/ transactions:\n if (!fSortedByFee &&\n ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 \/ 250)))\n {\n fSortedByFee = true;\n comparer = TxPriorityCompare(fSortedByFee);\n std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);\n }\n\n \/\/ Connecting shouldn't fail due to dependency on other memory pool transactions\n \/\/ because we're already processing them in order of dependency\n map mapTestPoolTmp(mapTestPool);\n MapPrevTx mapInputs;\n bool fInvalid;\n if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))\n continue;\n\n int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();\n if (nTxFees < nMinFee)\n continue;\n\n nTxSigOps += GetP2SHSigOpCount(tx, mapInputs);\n if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)\n continue;\n\n \/\/ Note that flags: we don't want to set mempool\/IsStandard()\n \/\/ policy here, but we still have to ensure that the block we\n \/\/ create only contains transactions that are valid in new blocks.\n if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true, MANDATORY_SCRIPT_VERIFY_FLAGS))\n continue;\n mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());\n swap(mapTestPool, mapTestPoolTmp);\n\n \/\/ Added\n pblock->vtx.push_back(tx);\n nBlockSize += nTxSize;\n ++nBlockTx;\n nBlockSigOps += nTxSigOps;\n nFees += nTxFees;\n\n if (fDebug && GetBoolArg(\"-printpriority\", false))\n {\n LogPrintf(\"priority %.1f feeperkb %.1f txid %s\\n\",\n dPriority, dFeePerKb, tx.GetHash().ToString());\n }\n\n \/\/ Add transactions that depend on this one to the priority queue\n uint256 hash = tx.GetHash();\n if (mapDependers.count(hash))\n {\n BOOST_FOREACH(COrphan* porphan, mapDependers[hash])\n {\n if (!porphan->setDependsOn.empty())\n {\n porphan->setDependsOn.erase(hash);\n if (porphan->setDependsOn.empty())\n {\n vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));\n std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);\n }\n }\n }\n }\n }\n\n nLastBlockTx = nBlockTx;\n nLastBlockSize = nBlockSize;\n\n if (fDebug && GetBoolArg(\"-printpriority\", false))\n LogPrintf(\"CreateNewBlock(): total size %u\\n\", nBlockSize);\n\n if (!fProofOfStake)\n pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(nHeight, nFees);\n\n if (pFees)\n *pFees = nFees;\n\n \/\/ Fill in header\n pblock->hashPrevBlock = pindexPrev->GetBlockHash();\n pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, pblock->GetMaxTransactionTime());\n if (!fProofOfStake)\n pblock->UpdateTime(pindexPrev);\n pblock->nNonce = 0;\n }\n\n return pblock.release();\n}\n\n\nvoid IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)\n{\n \/\/ Update nExtraNonce\n static uint256 hashPrevBlock;\n if (hashPrevBlock != pblock->hashPrevBlock)\n {\n nExtraNonce = 0;\n hashPrevBlock = pblock->hashPrevBlock;\n }\n ++nExtraNonce;\n\n unsigned int nHeight = pindexPrev->nHeight+1; \/\/ Height first in coinbase required for block.version=2\n pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;\n assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);\n\n pblock->hashMerkleRoot = pblock->BuildMerkleTree();\n}\n\n\nvoid FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)\n{\n \/\/\n \/\/ Pre-build hash buffers\n \/\/\n struct\n {\n struct unnamed2\n {\n int nVersion;\n uint256 hashPrevBlock;\n uint256 hashMerkleRoot;\n unsigned int nTime;\n unsigned int nBits;\n unsigned int nNonce;\n }\n block;\n unsigned char pchPadding0[64];\n uint256 hash1;\n unsigned char pchPadding1[64];\n }\n tmp;\n memset(&tmp, 0, sizeof(tmp));\n\n tmp.block.nVersion = pblock->nVersion;\n tmp.block.hashPrevBlock = pblock->hashPrevBlock;\n tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;\n tmp.block.nTime = pblock->nTime;\n tmp.block.nBits = pblock->nBits;\n tmp.block.nNonce = pblock->nNonce;\n\n FormatHashBlocks(&tmp.block, sizeof(tmp.block));\n FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));\n\n \/\/ Byte swap all the input buffer\n for (unsigned int i = 0; i < sizeof(tmp)\/4; i++)\n ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);\n\n \/\/ Precalc the first half of the first hash, which stays constant\n SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);\n\n memcpy(pdata, &tmp.block, 128);\n memcpy(phash1, &tmp.hash1, 64);\n}\n\n\nbool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)\n{\n uint256 hashBlock = pblock->GetHash();\n uint256 hashProof = pblock->GetPoWHash();\n uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();\n\n if(!pblock->IsProofOfWork())\n return error(\"CheckWork() : %s is not a proof-of-work block\", hashBlock.GetHex());\n\n if (hashProof > hashTarget)\n return error(\"CheckWork() : proof-of-work not meeting target\");\n\n \/\/\/\/ debug print\n LogPrintf(\"CheckWork() : new proof-of-work block found \\n proof hash: %s \\ntarget: %s\\n\", hashProof.GetHex(), hashTarget.GetHex());\n LogPrintf(\"%s\\n\", pblock->ToString());\n LogPrintf(\"generated %s\\n\", FormatMoney(pblock->vtx[0].vout[0].nValue));\n\n \/\/ Found a solution\n {\n LOCK(cs_main);\n if (pblock->hashPrevBlock != hashBestChain)\n return error(\"CheckWork() : generated block is stale\");\n\n \/\/ Remove key from key pool\n reservekey.KeepKey();\n\n \/\/ Track how many getdata requests this block gets\n {\n LOCK(wallet.cs_wallet);\n wallet.mapRequestCount[hashBlock] = 0;\n }\n\n \/\/ Process this block the same as if we had received it from another node\n if (!ProcessBlock(NULL, pblock))\n return error(\"CheckWork() : ProcessBlock, block not accepted\");\n }\n\n return true;\n}\n\nbool CheckStake(CBlock* pblock, CWallet& wallet)\n{\n uint256 proofHash = 0, hashTarget = 0;\n uint256 hashBlock = pblock->GetHash();\n\n if(!pblock->IsProofOfStake())\n return error(\"CheckStake() : %s is not a proof-of-stake block\", hashBlock.GetHex());\n\n \/\/ verify hash target and signature of coinstake tx\n if (!CheckProofOfStake(mapBlockIndex[pblock->hashPrevBlock], pblock->vtx[1], pblock->nBits, proofHash, hashTarget))\n return error(\"CheckStake() : proof-of-stake checking failed\");\n\n \/\/\/\/ debug print\n LogPrintf(\"CheckStake() : new proof-of-stake block found \\n hash: %s \\nproofhash: %s \\ntarget: %s\\n\", hashBlock.GetHex(), proofHash.GetHex(), hashTarget.GetHex());\n LogPrintf(\"%s\\n\", pblock->ToString());\n LogPrintf(\"out %s\\n\", FormatMoney(pblock->vtx[1].GetValueOut()));\n\n \/\/ Found a solution\n {\n LOCK(cs_main);\n if (pblock->hashPrevBlock != hashBestChain)\n return error(\"CheckStake() : generated block is stale\");\n\n \/\/ Track how many getdata requests this block gets\n {\n LOCK(wallet.cs_wallet);\n wallet.mapRequestCount[hashBlock] = 0;\n }\n\n \/\/ Process this block the same as if we had received it from another node\n if (!ProcessBlock(NULL, pblock))\n return error(\"CheckStake() : ProcessBlock, block not accepted\");\n }\n\n return true;\n}\n\nvoid ThreadStakeMiner(CWallet *pwallet)\n{\n SetThreadPriority(THREAD_PRIORITY_LOWEST);\n\n \/\/ Make this thread recognisable as the mining thread\n RenameThread(\"sumcoin-miner\");\n\n CReserveKey reservekey(pwallet);\n\n bool fTryToSync = true;\n\n while (true)\n {\n while (pwallet->IsLocked())\n {\n nLastCoinStakeSearchInterval = 0;\n MilliSleep(1000);\n }\n\n while (vNodes.empty() || IsInitialBlockDownload())\n {\n nLastCoinStakeSearchInterval = 0;\n fTryToSync = true;\n MilliSleep(1000);\n }\n\n if (fTryToSync)\n {\n fTryToSync = false;\n if (vNodes.size() < 3 || pindexBest->GetBlockTime() < GetTime() - 10 * 60)\n {\n MilliSleep(60000);\n continue;\n }\n }\n\n \/\/\n \/\/ Create new block\n \/\/\n int64_t nFees;\n unique_ptr pblock(CreateNewBlock(reservekey, true, &nFees));\n if (!pblock.get())\n return;\n\n \/\/ Trying to sign a block\n if (pblock->SignBlock(*pwallet, nFees))\n {\n SetThreadPriority(THREAD_PRIORITY_NORMAL);\n CheckStake(pblock.get(), *pwallet);\n SetThreadPriority(THREAD_PRIORITY_LOWEST);\n MilliSleep(500);\n }\n else\n MilliSleep(nMinerSleep);\n }\n}\n","avg_line_length":34.452173913,"max_line_length":170,"alphanum_fraction":0.582382635} {"size":5196,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \"DataStruct\/DateTime.h\"\n\nnamespace PetAPI {\n\n\/*------------Date------------*\/\n\nDate::Date(int y, int m, int d) {\n\tyear = y;\n\tmonth = m;\n\tday = d;\n}\n\nDate::Date(const Date & date) {\n\tyear = date.year;\n\tmonth = date.month;\n\tday = date.day;\n}\n\nDate Date::currentDate() {\n\tDate ret;\n#ifdef _WIN32\n\tSYSTEMTIME date;\n\tGetLocalTime(&date);\n\tret.year = date.wYear;\n\tret.month = date.wMonth;\n\tret.day = date.wDay;\n#else\n\t\/\/TODO: get current date for linux\n#endif\n\treturn ret;\n}\n\nDate Date::fromByteBuffer(const ByteBuffer & buffer, size_t from) {\n\tDate data;\n\tif (buffer.empty()) return data;\n\tif (buffer.size() < 12) return data;\n\tif (buffer.size() - from < 12) return data;\n\tif (buffer.size() <= from) return data;\n\t\n\tbuffer.parseVariable(from, data.year);\n\tbuffer.parseVariable(from + 4, data.month);\n\tbuffer.parseVariable(from + 8, data.day);\n\treturn data;\n}\n\nstd::string Date::toString(DateFormat format, DTSeparator separator) {\n\tif (separator == DTSeparator::COLON) return \"\";\n\tswitch (format) {\n\tcase DateFormat::YYYYMMDD:\n\t\treturn std::to_string(year) + static_cast(separator) +\n\t\t (month < 10 ? '0' + std::to_string(month) : std::to_string(month)) +\n\t\t static_cast(separator) +\n\t\t (day < 10 ? '0' + std::to_string(day) : std::to_string(day));\n\tcase DateFormat::YYYYDDMM:\n\t\treturn std::to_string(year) + static_cast(separator) +\n\t\t (day < 10 ? '0' + std::to_string(day) : std::to_string(day)) +\n\t\t static_cast(separator) +\n\t\t (month < 10 ? '0' + std::to_string(month) : std::to_string(month));\n\tcase DateFormat::DDMMYYYY:\n\t\treturn (day < 10 ? '0' + std::to_string(day) : std::to_string(day)) +\n\t\t static_cast(separator) +\n\t\t (month < 10 ? '0' + std::to_string(month) : std::to_string(month)) +\n\t\t static_cast(separator) +\n\t\t std::to_string(year);\n\tcase DateFormat::DMYYYY:\n\t\treturn std::to_string(day) + static_cast(separator) +\n\t\t std::to_string(month) + static_cast(separator) +\n\t\t std::to_string(year);\n\tcase DateFormat::MDYYYY:\n\t\treturn std::to_string(month) + static_cast(separator) +\n\t\t std::to_string(day) + static_cast(separator) +\n\t\t std::to_string(year);\n\tcase DateFormat::YYYYMD:\n\t\treturn std::to_string(year) + static_cast(separator) +\n\t\t std::to_string(month) + static_cast(separator) +\n\t\t std::to_string(day);\n\t}\n}\n\nByteBuffer Date::toByteBuffer() {\n\tByteBuffer buffer;\n\tbuffer.appendVariable(year);\n\tbuffer.appendVariable(month);\n\tbuffer.appendVariable(day);\n\treturn buffer;\n}\n\nsize_t Date::toByteBuffer(ByteBuffer & buffer) {\n\tbuffer.appendVariable(year);\n\tbuffer.appendVariable(month);\n\tbuffer.appendVariable(day);\n\treturn 12;\n}\n\nbool Date::operator==(const Date & date) {\n\tif (date.year != year) return false;\n\tif (date.month != month) return false;\n\tif (date.day != day) return false;\n\treturn true;\n}\n\nbool Date::operator!=(const Date & date) {\n\treturn !operator==(date);\n}\n\n\/*------------Time------------*\/\n\nTime::Time(int h, int m, int s) {\n\thour = h;\n\tminute = m;\n\tsecond = s;\n}\n\nTime::Time(const Time & time) {\n\thour = time.hour;\n\tminute = time.minute;\n\tsecond = time.second;\n}\n\nTime Time::currentTime() {\n\tTime ret;\n#ifdef _WIN32\n\tSYSTEMTIME time;\n\tGetLocalTime(&time);\n\tret.hour = time.wHour;\n\tret.minute = time.wMinute;\n\tret.second = time.wSecond;\n#else\n\t\/\/TODO: get current time for linux\n#endif\n\treturn ret;\n}\n\nTime Time::fromByteBuffer(const ByteBuffer & buffer, size_t from) {\n\tTime time;\n\tif (buffer.empty()) return time;\n\tif (buffer.size() < 12) return time;\n\tif (buffer.size() - from < 12) return time;\n\tif (buffer.size() <= from) return time;\n\t\n\tbuffer.parseVariable(from, time.hour);\n\tbuffer.parseVariable(from + 4, time.minute);\n\tbuffer.parseVariable(from + 8, time.second);\n\treturn time;\n}\n\nstd::string Time::toString(TimeFormat format) {\n\tswitch (format) {\n\tcase TimeFormat::Russia:\n\t\treturn (hour < 10 ? \"0\" : \"\") + std::to_string(hour) + static_cast(DTSeparator::COLON) +\n\t\t (minute < 10 ? \"0\" : \"\") + std::to_string(minute) + static_cast(DTSeparator::COLON) +\n\t\t (second < 10 ? \"0\" : \"\") + std::to_string(second);\n\tcase TimeFormat::USA: break;\n\t\treturn (hour < 10 ? \"0\" : \"\") + std::to_string(hour > 12 ? hour - 12 : hour) + static_cast(DTSeparator::COLON) +\n\t\t (minute < 10 ? \"0\" : \"\") + std::to_string(minute) + static_cast(DTSeparator::COLON) +\n\t\t (second < 10 ? \"0\" : \"\") + std::to_string(second) + (hour > 12 ? \" pm\" : \" am\");\n\t}\n}\n\nByteBuffer Time::toByteBuffer() {\n\tByteBuffer buffer;\n\tbuffer.appendVariable(hour);\n\tbuffer.appendVariable(minute);\n\tbuffer.appendVariable(second);\n\treturn buffer;\n}\n\nsize_t Time::toByteBuffer(ByteBuffer & buffer) {\n\tbuffer.appendVariable(hour);\n\tbuffer.appendVariable(minute);\n\tbuffer.appendVariable(second);\n\treturn 12;\n}\n\nbool Time::operator==(const Time & time) {\n\tif (time.hour != hour) return false;\n\tif (time.minute != minute) return false;\n\tif (time.second != second) return false;\n\treturn true;\n}\n\nbool Time::operator!=(const Time & time) {\n\treturn !operator==(time);\n}\n\n}\n","avg_line_length":27.7860962567,"max_line_length":120,"alphanum_fraction":0.6485758276} {"size":1810,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n#include \n#include \"halfedge.h\"\n#include \"triangle.h\"\n#include \"vertex.h\"\n\n\nHalfEdge::HalfEdge(Mesh* mesh_in, Vertex* v0_in, Vertex* v1_in,\n Triangle* triangle_in,\n unsigned id_on_tri_of_v0) : MeshAttribute( mesh_in, id_on_tri_of_v0) {\n mesh->n_halfedges++;\n v0 = v0_in;\n v1 = v1_in;\n triangle = triangle_in;\n halfedge = v1->halfedge_to_vertex(v0);\n switch (id_on_tri_of_v0) {\n case 0:\n v0_tri_i = 0;\n v1_tri_i = 1;\n v2_tri_i = 2;\n v2 = triangle->v2;\n break;\n case 1:\n v0_tri_i = 1;\n v1_tri_i = 2;\n v2_tri_i = 0;\n v2 = triangle->v0;\n break;\n case 2:\n v0_tri_i = 2;\n v1_tri_i = 0;\n v2_tri_i = 1;\n v2 = triangle->v1;\n break;\n }\n if (halfedge != NULL) {\n \/\/ setting opposite halfedge to me\n halfedge->halfedge = this;\n mesh->n_fulledges++;\n }\n else {\n \/\/ first time weve encountered this\n mesh_in->add_edge(this);\n }\n}\n\nHalfEdge::~HalfEdge(){}\n\nbool HalfEdge::part_of_fulledge() {\n if (halfedge != NULL) {\n return true;\n }\n else {\n return false;\n }\n}\n\nHalfEdge* HalfEdge::ccw_around_tri() {\n HalfEdge* he = NULL;\n if (v1->id == triangle->v0->id) {\n he = triangle->e0;\n }\n else if (v1->id == triangle->v1->id) {\n he = triangle->e1;\n }\n else if (v1->id == triangle->v2->id) {\n he = triangle->e2;\n }\n else {\n std::cout << \"ERROR: cannot find HE!\" << std::endl;\n }\n return he;\n}\n\ndouble HalfEdge::length() {\n \/\/ TODO actually calcuate this\n std::cout << \"This isn't actually calculating the length\" << std::endl;\n return 1.0;\n}\n\n","avg_line_length":22.3456790123,"max_line_length":78,"alphanum_fraction":0.520441989} {"size":2182,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::begin;\nusing std::end;\nusing std::string;\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::get;\nusing std::vector;\nusing IntVec = std::vector;\n\nstring STATE0{\"#...##.#...#..#.#####.##.#..###.#.#.###....#...#...####.#....##..##..#..#..#..#.#..##.####.#.#.###\"};\n\nstring RULES {R\"(..... => .\n..#.. => #\n..##. => #\n#..## => .\n..#.# => #\n####. => .\n##.## => .\n#.... => .\n###.. => #\n##### => #\n##..# => #\n#.### => #\n#..#. => #\n.#### => #\n#.#.. => #\n.###. => #\n.##.. => #\n.#... => #\n.#.## => #\n##... => #\n..### => .\n##.#. => .\n...## => .\n....# => .\n###.# => .\n#.##. => #\n.##.# => .\n.#..# => #\n#.#.# => #\n.#.#. => #\n...#. => #\n#...# => #)\" };\n\n\nauto value(const std::string& s)\n{\n int v{0};\n for (auto ch : s)\n {\n v = v * 2 + (ch == '#');\n }\n return v;\n};\n\n\n\nauto task1(string state, string rules0)\n{\n\n std::istringstream iss(rules0);\n string s, dummy, res;\n\n vector rules(32, 0);\n\n while (iss >> s)\n {\n iss >> dummy;\n iss >> res;\n if (res[0] == '#')\n {\n rules[value(s)] = 1;\n }\n \/\/cout << s << endl;\n }\n\n auto prev{STATE0 + \"....\"};\n \/\/auto prev{STATE0};\n \/\/prev += \"....\";\n auto pos{0};\n char token[2] = { '.', '#' };\n \n cout << endl;\n cout << prev << \":\" << pos << \";\" << prev.length() << endl;\n for (auto j = 1; j <= 20; ++j)\n {\n auto val{0u};\n string s;\n int plen {static_cast(prev.length())};\n \/\/s.reserve(prev.length() + 4);\n s.reserve(plen + 4);\n \n for (auto i = -4; i < plen - 4; ++i)\n {\n val = (val * 2 + (prev[i + 4] == '#')) & 31; \n s += token[rules[val]];\n }\n s += \"....\";\n pos -= 2;\n cout << s << \" , \" << j << \", \" << pos << endl;\n prev = s;\n }\n\n int result{0};\n for (auto ch : prev)\n {\n result += (ch == '#') * pos;\n ++pos;\n }\n\n return result;\n}\n\nint main()\n{\n auto t = task1(STATE0, RULES);\n cout << t << endl;\n return 0;\n}\n","avg_line_length":16.9147286822,"max_line_length":116,"alphanum_fraction":0.3510540788} {"size":3478,"ext":"cpp","lang":"C++","max_stars_count":111.0,"content":"\ufeff\/**\n * Copyright(c) Live2D Inc. All rights reserved.\n *\n * Use of this source code is governed by the Live2D Open Software license\n * that can be found at https:\/\/www.live2d.com\/eula\/live2d-open-software-license-agreement_en.html.\n *\/\n\n#include \"LAppPal.hpp\"\n#include \n#include \n#include \n#include \"LAppDefine.hpp\"\n#include \"LAppDelegate.hpp\"\n\nusing namespace Csm;\nusing namespace std;\nusing namespace LAppDefine;\n\nnamespace {\n LARGE_INTEGER s_frequency;\n LARGE_INTEGER s_lastFrame;\n double s_deltaTime = 0.0;\n}\n\nvoid LAppPal::StartTimer()\n{\n QueryPerformanceFrequency(&s_frequency);\n}\n\ncsmByte* LAppPal::LoadFileAsBytes(const string filePath, csmSizeInt* outSize)\n{\n \/\/filePath;\/\/\n const char* path = filePath.c_str();\n\n int size = 0;\n struct stat statBuf;\n if (stat(path, &statBuf) == 0)\n {\n size = statBuf.st_size;\n }\n\n std::fstream file;\n char* buf = new char[size];\n\n file.open(path, std::ios::in | std::ios::binary);\n if (!file.is_open())\n {\n if (DebugLogEnable)\n {\n PrintLog(\"file open error\");\n }\n return NULL;\n }\n file.read(buf, size);\n file.close();\n\n *outSize = size;\n return reinterpret_cast(buf);\n}\n\nvoid LAppPal::ReleaseBytes(csmByte* byteData)\n{\n delete[] byteData;\n}\n\ncsmFloat32 LAppPal::GetDeltaTime()\n{\n return static_cast(s_deltaTime);\n}\n\nvoid LAppPal::UpdateTime()\n{\n if (s_frequency.QuadPart == 0)\n {\n StartTimer();\n QueryPerformanceCounter(&s_lastFrame);\n s_deltaTime = 0.0f;\n return;\n }\n\n LARGE_INTEGER current;\n QueryPerformanceCounter(¤t);\n\n const LONGLONG BASIS = 1000000;\n LONGLONG dwTime = ((current.QuadPart - s_lastFrame.QuadPart) * (LONGLONG)BASIS \/ s_frequency.QuadPart);\n s_deltaTime = (double)dwTime \/ (double)(BASIS);\n s_lastFrame = current;\n}\n\nvoid LAppPal::PrintLog(const char* format, ...)\n{\n va_list args;\n char buf[256];\n va_start(args, format);\n _vsnprintf_s(buf, sizeof(buf), format, args);\n OutputDebugStringA((LPCSTR)buf);\n OutputDebugStringA(\"\\n\"); \/\/ \u6539\u884c\u3092\u5225\u9014\u4ed8\u4e0e\u3057\u307e\u3059\n va_end(args);\n}\n\nvoid LAppPal::PrintLogW(const wchar_t* format, ...)\n{\n va_list args;\n wchar_t buf[256];\n va_start(args, format);\n _vsnwprintf_s(buf, sizeof(buf), format, args);\n OutputDebugString((LPCSTR)buf);\n OutputDebugString(\"\\n\"); \/\/ \u6539\u884c\u3092\u5225\u9014\u4ed8\u4e0e\u3057\u307e\u3059\n va_end(args);\n}\n\nvoid LAppPal::PrintMessage(const csmChar* message)\n{\n PrintLog(\"%s\", message);\n}\n\nvoid LAppPal::CoordinateFullScreenToWindow(float clientWidth, float clientHeight, float fullScreenX, float fullScreenY, float& retWindowX, float& retWindowY)\n{\n retWindowX = retWindowY = 0.0f;\n\n const float width = static_cast(clientWidth);\n const float height = static_cast(clientHeight);\n\n if (width == 0.0f || height == 0.0f) return;\n\n retWindowX = (fullScreenX + width) * 0.5f;\n retWindowY = (-fullScreenY + height) * 0.5f;\n}\n\nvoid LAppPal::CoordinateWindowToFullScreen(float clientWidth, float clientHeight, float windowX, float windowY, float& retFullScreenX, float& retFullScreenY)\n{\n retFullScreenX = retFullScreenY = 0.0f;\n\n const float width = static_cast(clientWidth);\n const float height = static_cast(clientHeight);\n\n if (width == 0.0f || height == 0.0f) return;\n\n retFullScreenX = 2.0f * windowX - width;\n retFullScreenY = (2.0f * windowY - height) * -1.0f;\n}\n","avg_line_length":24.4929577465,"max_line_length":157,"alphanum_fraction":0.6687751581} {"size":477,"ext":"cc","lang":"C++","max_stars_count":1.0,"content":"class Solution {\nprivate :\n\tconst int none = 0;\npublic:\n\tvector findDuplicates(vector& nums) {\n\t\tvector ret;\n\n\t\tfor (int i = 0; i < nums.size();) {\n\t\t\tint idx = nums[i] - 1;\n\t\t\tif ((i == idx) || (nums[i] == none)) {\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (nums[idx] == nums[i]) {\n\t\t\t\tret.push_back(nums[i]);\n\t\t\t\tnums[idx] = none;\n\t\t\t\tnums[i] = none;\n\t\t\t\t++i;\n\t\t\t} else {\n\t\t\t\tint j = nums[i];\n\t\t\t\tnums[i] = nums[idx];\n\t\t\t\tnums[idx] = j;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n};\n","avg_line_length":15.9,"max_line_length":48,"alphanum_fraction":0.4905660377} {"size":3947,"ext":"cpp","lang":"C++","max_stars_count":null,"content":"\/\/=================================================================================================\n\/*!\n\/\/ \\file src\/mathtest\/dmatsmatsub\/M7x13bMCb.cpp\n\/\/ \\brief Source file for the M7x13bMCb dense matrix\/sparse matrix subtraction math test\n\/\/\n\/\/ Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved\n\/\/\n\/\/ This file is part of the Blaze library. You can redistribute it and\/or modify it under\n\/\/ the terms of the New (Revised) BSD License. Redistribution and use in source and binary\n\/\/ forms, with or without modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/ conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/ of conditions and the following disclaimer in the documentation and\/or other materials\n\/\/ provided with the distribution.\n\/\/ 3. Neither the names of the Blaze development group nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n\/\/ SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n\/\/ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n\/\/ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n*\/\n\/\/=================================================================================================\n\n\n\/\/*************************************************************************************************\n\/\/ Includes\n\/\/*************************************************************************************************\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/=================================================================================================\n\/\/\n\/\/ MAIN FUNCTION\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\nint main()\n{\n std::cout << \" Running 'M7x13bMCb'...\" << std::endl;\n\n using blazetest::mathtest::TypeB;\n\n try\n {\n \/\/ Matrix type definitions\n typedef blaze::StaticMatrix M7x13b;\n typedef blaze::CompressedMatrix MCb;\n\n \/\/ Creator type definitions\n typedef blazetest::Creator CM7x13b;\n typedef blazetest::Creator CMCb;\n\n \/\/ Running the tests\n RUN_DMATSMATSUB_OPERATION_TEST( CM7x13b(), CMCb( 7UL, 13UL, 0UL ) );\n RUN_DMATSMATSUB_OPERATION_TEST( CM7x13b(), CMCb( 7UL, 13UL, 30UL ) );\n RUN_DMATSMATSUB_OPERATION_TEST( CM7x13b(), CMCb( 7UL, 13UL, 60UL ) );\n RUN_DMATSMATSUB_OPERATION_TEST( CM7x13b(), CMCb( 7UL, 13UL, 91UL ) );\n }\n catch( std::exception& ex ) {\n std::cerr << \"\\n\\n ERROR DETECTED during dense matrix\/sparse matrix subtraction:\\n\"\n << ex.what() << \"\\n\";\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\/\/*************************************************************************************************\n","avg_line_length":45.367816092,"max_line_length":99,"alphanum_fraction":0.5730934887} {"size":593,"ext":"hpp","lang":"C++","max_stars_count":null,"content":"#ifndef BINARY_THRESHOLDING_HPP\n#define BINARY_THRESHOLDING_HPP\n\n#include \"FAST\/Algorithms\/SegmentationAlgorithm.hpp\"\n\nnamespace fast {\n\nclass FAST_EXPORT BinaryThresholding : public SegmentationAlgorithm {\n FAST_OBJECT(BinaryThresholding)\n public:\n void setLowerThreshold(float threshold);\n void setUpperThreshold(float threshold);\n private:\n BinaryThresholding();\n void execute();\n void waitToFinish();\n\n float mLowerThreshold;\n float mUpperThreshold;\n bool mLowerThresholdSet;\n bool mUpperThresholdSet;\n};\n\n}\n\n#endif\n","avg_line_length":21.962962963,"max_line_length":70,"alphanum_fraction":0.7133220911} {"size":5607,"ext":"cpp","lang":"C++","max_stars_count":3710.0,"content":"\n#include \"viewtools.h\"\n\n#include \"tools\/cursors.h\"\n#include \"tgeometry.h\"\n\n#include \n\n#include \"tgl.h\"\n\nnamespace {\n\n\/\/=============================================================================\n\/\/ Zoom Tool\n\/\/-----------------------------------------------------------------------------\n\nclass ZoomTool final : public TTool {\n int m_oldY;\n TPointD m_center;\n bool m_dragging;\n double m_factor;\n\npublic:\n ZoomTool() : TTool(\"T_Zoom\"), m_dragging(false), m_oldY(0), m_factor(1) {\n bind(TTool::AllTargets);\n }\n\n ToolType getToolType() const override { return TTool::GenericTool; }\n\n void updateMatrix() override { return setMatrix(TAffine()); }\n\n void leftButtonDown(const TPointD &pos, const TMouseEvent &e) override {\n if (!m_viewer) return;\n m_dragging = true;\n int v = 1;\n if (e.isAltPressed()) v = -1;\n m_oldY = e.m_pos.y;\n \/\/ m_center = getViewer()->winToWorld(e.m_pos);\n m_center = TPointD(e.m_pos.x, e.m_pos.y);\n m_factor = 1;\n invalidate();\n }\n void leftButtonDrag(const TPointD &pos, const TMouseEvent &e) override {\n int d = m_oldY - e.m_pos.y;\n m_oldY = e.m_pos.y;\n double f = exp(-d * 0.01);\n m_factor = f;\n m_viewer->zoom(m_center, f);\n }\n void leftButtonUp(const TPointD &pos, const TMouseEvent &e) override {\n m_dragging = false;\n invalidate();\n }\n\n void rightButtonDown(const TPointD &, const TMouseEvent &e) override {\n if (!m_viewer) return;\n invalidate();\n }\n\n void draw() override {\n if (!m_dragging) return;\n\n TPointD center = m_viewer->winToWorld(m_center);\n double pixelSize = getPixelSize();\n double unit = pixelSize;\n glPushMatrix();\n glTranslated(center.x, center.y, 0);\n glScaled(unit, unit, unit);\n glColor3f(1, 0, 0);\n\n double u = 4;\n glBegin(GL_LINES);\n glVertex2d(0, -10);\n glVertex2d(0, 10);\n glVertex2d(-10, 0);\n glVertex2d(10, 0);\n glEnd();\n\n glPopMatrix();\n }\n\n int getCursorId() const override { return ToolCursor::ZoomCursor; }\n\n} zoomTool;\n\n\/\/=============================================================================\n\/\/ Hand Tool\n\/\/-----------------------------------------------------------------------------\n\nclass HandTool final : public TTool {\n TStopWatch m_sw;\n TPointD m_oldPos;\n\npublic:\n HandTool() : TTool(\"T_Hand\") { bind(TTool::AllTargets); }\n\n ToolType getToolType() const override { return TTool::GenericTool; }\n\n void updateMatrix() override { return setMatrix(TAffine()); }\n\n void leftButtonDown(const TPointD &pos, const TMouseEvent &e) override {\n if (!m_viewer) return;\n m_oldPos = e.m_pos;\n m_sw.start(true);\n }\n\n void leftButtonDrag(const TPointD &pos, const TMouseEvent &e) override {\n if (!m_viewer) return;\n if (m_sw.getTotalTime() < 10) return;\n m_sw.stop();\n m_sw.start(true);\n TPointD delta = e.m_pos - m_oldPos;\n delta.y = -delta.y;\n m_viewer->pan(delta);\n m_oldPos = e.m_pos;\n }\n\n void leftButtonUp(const TPointD &pos, const TMouseEvent &e) override {\n if (!m_viewer) return;\n m_sw.stop();\n }\n\n int getCursorId() const override { return ToolCursor::PanCursor; }\n\n} handTool;\n\n} \/\/ namespace\n\n\/\/=============================================================================\n\/\/ Rotate Tool\n\/\/-----------------------------------------------------------------------------\n\nRotateTool::RotateTool()\n : TTool(\"T_Rotate\")\n , m_dragging(false)\n , m_cameraCentered(\"Rotate On Camera Center\", false)\n , m_angle(0) {\n bind(TTool::AllTargets);\n m_prop.bind(m_cameraCentered);\n}\n\nvoid RotateTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {\n if (!m_viewer) return;\n\n m_angle = 0.0;\n m_dragging = true;\n m_oldPos = pos;\n m_oldMousePos = e.m_pos;\n \/\/ m_center = TPointD(0,0);\n m_sw.start(true);\n invalidate();\n\n \/\/ m_center =\n \/\/ viewAffine.inv()*TPointD(0,0);\/\/m_viewer->winToWorld(m_viewer);\n \/\/ virtual TPointD winToWorld(const TPoint &winPos) const = 0;\n}\n\nvoid RotateTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {\n if (!m_viewer) return;\n if (m_sw.getTotalTime() < 50) return;\n m_sw.stop();\n m_sw.start(true);\n TPointD p = pos;\n if (m_viewer->is3DView()) {\n TPointD d = e.m_pos - m_oldMousePos;\n m_oldMousePos = e.m_pos;\n double factor = 0.5;\n m_viewer->rotate3D(factor * d.x, -factor * d.y);\n } else {\n TPointD a = p - m_center;\n TPointD b = m_oldPos - m_center;\n if (norm2(a) > 0 && norm2(b) > 0) {\n double ang = asin(cross(b, a) \/ (norm(a) * norm(b))) * M_180_PI;\n m_angle = m_angle + ang;\n m_viewer->rotate(m_center, m_angle);\n }\n }\n m_oldPos = p;\n}\n\nvoid RotateTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {\n m_dragging = false;\n invalidate();\n m_sw.stop();\n}\n\nvoid RotateTool::draw() {\n glColor3f(1, 0, 0);\n double u = 50;\n if (m_cameraCentered.getValue())\n m_center = TPointD(0, 0);\n else {\n TAffine aff = m_viewer->getViewMatrix().inv();\n if (m_viewer->getIsFlippedX()) aff = aff * TScale(-1, 1);\n if (m_viewer->getIsFlippedY()) aff = aff * TScale(1, -1);\n u = u * sqrt(aff.det());\n m_center = aff * TPointD(0, 0);\n }\n tglDrawSegment(TPointD(-u + m_center.x, m_center.y),\n TPointD(u + m_center.x, m_center.y));\n tglDrawSegment(TPointD(m_center.x, -u + m_center.y),\n TPointD(m_center.x, u + m_center.y));\n}\n\nint RotateTool::getCursorId() const { return ToolCursor::RotateCursor; }\n\nRotateTool rotateTool;","avg_line_length":27.0869565217,"max_line_length":79,"alphanum_fraction":0.5685749955} {"size":878,"ext":"cp","lang":"C++","max_stars_count":null,"content":"module List\n\nfun length x = match x { | [] -> 0 | _:xs -> 1 + length xs }\nfun map f x = match x {\n | [] -> []\n | x:xs -> f x : map f xs\n}\nfun append x y = match x {\n | [] -> y\n | x:xs -> x : append xs y\n}\nfun reverse x = match x {\n | [] -> []\n | x:xs -> append (reverse xs) [x]\n}\nfun filter p x = match x {\n | [] -> []\n | x:xs ->\n if p x then\n x : filter p xs\n else\n filter p xs\n}\n\n\/*\nfun length x =\n if x == [] then\n 0\n else\n 1 + length (tl x)\n\nfun map f x =\n if x == [] then []\n else f (hd x) : map f (tl x)\n\nfun append x y =\n if x == [] then y\n else (hd x) : append (tl x) y\n\nfun reverse x =\n if x == [] then []\n else append (reverse (tl x)) [hd x]\n\nfun filter p x =\n if x == [] then []\n else if p (hd x) then\n (hd x) : filter p (tl x)\n else filter p (tl x)\n*\/\n","avg_line_length":17.56,"max_line_length":60,"alphanum_fraction":0.4328018223}