/// <summary> /// Called if touches are removed. /// </summary> /// <param name="touches">The touches.</param> protected virtual void touchesEnded(IList <ITouch> touches) { if (combineTouches) { foreach (var touch in touches) { touchSequence.Add(touch); } if (activeTouches.Count == 0) { // Checking which points were removed in clusterExistenceTime seconds to set their centroid as cached screen position var cluster = touchSequence.FindElementsLaterThan(Time.time - combineTouchesInterval, shouldCacheTouchPosition); cachedScreenPosition = ClusterUtils.Get2DCenterPosition(cluster); cachedPreviousScreenPosition = ClusterUtils.GetPrevious2DCenterPosition(cluster); } } else { if (activeTouches.Count == 0) { var lastPoint = touches[touches.Count - 1]; if (shouldCacheTouchPosition(lastPoint)) { cachedScreenPosition = lastPoint.Position; cachedPreviousScreenPosition = lastPoint.PreviousPosition; } else { cachedScreenPosition = TouchManager.INVALID_POSITION; cachedPreviousScreenPosition = TouchManager.INVALID_POSITION; } } } }
/// <inheritdoc /> protected override void pointersReleased(IList <Pointer> pointers) { #if UNITY_5_6_OR_NEWER gestureSampler.Begin(); #endif base.pointersReleased(pointers); if (combinePointers) { var count = pointers.Count; for (var i = 0; i < count; i++) { pointerSequence.Add(pointers[i]); } if (NumPointers == 0) { // Checking which points were removed in clusterExistenceTime seconds to set their centroid as cached screen position var cluster = pointerSequence.FindElementsLaterThan(Time.unscaledTime - combinePointersInterval, shouldCachePointerPosition); cachedScreenPosition = ClusterUtils.Get2DCenterPosition(cluster); cachedPreviousScreenPosition = ClusterUtils.GetPrevious2DCenterPosition(cluster); } } else { if (NumPointers == 0) { if (!isActive) { setState(GestureState.Failed); #if UNITY_5_6_OR_NEWER gestureSampler.End(); #endif return; } // pointers outside of gesture target are ignored in shouldCachePointerPosition() // if all pointers are outside ScreenPosition will be invalid if (TouchManager.IsInvalidPosition(ScreenPosition)) { setState(GestureState.Failed); } else { tapsDone++; isActive = false; if (tapsDone >= numberOfTapsRequired) { setState(GestureState.Recognized); } } } } #if UNITY_5_6_OR_NEWER gestureSampler.End(); #endif }
void ParseSceneData(string sceneName) { clusters = ClusterUtils.ReadBytes <Cluster>(PATH_FOLDER + "/" + sceneName + "/" + PATH_CLUSTER + sceneName); if (clusters == null || clusters.Length == 0) { Debug.LogError("场景数据初始化失败,请检查文件路径或者二进制文件是否存在"); } }
/// <inheritdoc /> protected override Vector2 getPointPreviousScreenPosition(int index) { if (!clusters.HasClusters) { return(ClusterUtils.GetPrevious2DCenterPosition(activeTouches)); } return(clusters.GetPreviousCenterPosition(index)); }
/// <inheritdoc /> protected override Vector2 getPointScreenPosition(int index) { if (!clusters.HasClusters) { return(ClusterUtils.Get2DCenterPosition(activePointers)); } return(clusters.GetCenterPosition(index)); }
private void WriteToFile(out string[] strs, List <Texture> list, int typeIndex, string path) { strs = new string[list.Count]; for (int i = 0; i < list.Count; i++) { strs[i] = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(list[i])); ComputeBuffer floatBuffer = new ComputeBuffer(list[i].width * list[i].height, sizeof(float4)); Texture tex = list[i]; int pass = typeIndex == 0 ? 0 : 1;// 正常纹理和法线纹理 TextureProcess.SetBuffer(pass, "_TextureDatas", floatBuffer); TextureProcess.SetTexture(pass, "_TargetTexture", tex); TextureProcess.SetInt("_Width", tex.width); TextureProcess.SetInt("_Height", tex.height); TextureProcess.SetInt("_Offset", 0); TextureProcess.Dispatch(pass, tex.width / 8, tex.height / 8, 1); float4[] resultDatas = new float4[floatBuffer.count]; floatBuffer.GetData(resultDatas); string savePath = path + ClusterComponents.PATH_TEX_BYTES; ClusterUtils.CheckPath(savePath); savePath += strs[i] + ".bytes"; switch (typeIndex) { case 0: byte[] albedoColors = new byte[resultDatas.Length * sizeof(Color32)]; Color32 *albedoColorsPtr = (Color32 *)(UnsafeUtility.AddressOf(ref albedoColors[0])); for (int j = 0; j < resultDatas.Length; ++j) { float4 v = resultDatas[j]; albedoColorsPtr[j] = new Color32((byte)(v.x * 255), (byte)(v.y * 255), (byte)(v.z * 255), (byte)(v.w * 255)); } break; case 1: byte[] normalColors = new byte[resultDatas.Length * sizeof(half2)]; half2 *normalColorsPtr = (half2 *)(UnsafeUtility.AddressOf(ref normalColors[0])); for (int j = 0; j < resultDatas.Length; ++j) { float4 v = resultDatas[j]; normalColorsPtr[j] = (half2)v.xy; } break; } ClusterUtils.WriteBytes(savePath, resultDatas); floatBuffer.Dispose(); } }
void ParseSceneData(string sceneName) { points = ClusterUtils.ReadBytes <Point>(PATH_FOLDER + "/" + sceneName + "/" + PATH_VERTEX + sceneName); if (points == null || points.Length == 0) { Debug.LogError("场景数据初始化失败,请检查文件路径或者二进制文件是否存在"); } // 初始化全局参数 if (instanceCount < 1) { instanceCount = 1; } instanceCount = points.Length / CLUSTERCLIPCOUNT + (points.Length % CLUSTERCLIPCOUNT > 0 ? 1 : 0); vertexCount = CLUSTERCLIPCOUNT; // 顶点坐标应该是包含index信息的顶点坐标 }
private void Do() { Scene scene = SceneManager.GetActiveScene(); sceneName = scene.name.Replace("workscene_", ""); LODGroup[] groups = GetComponentsInChildren <LODGroup>(); Dictionary <MeshRenderer, bool> lowLevelDict = new Dictionary <MeshRenderer, bool>(); foreach (var i in groups) { LOD[] lods = i.GetLODs(); for (int j = 1; j < lods.Length; ++j) { foreach (var k in lods[j].renderers) { if (k.GetType() == typeof(MeshRenderer)) { lowLevelDict.Add(k as MeshRenderer, true); } } } } resPath = PATH_FOLDER + sceneName + "/"; CombinedModel model = ProcessCluster(GetComponentsInChildren <MeshRenderer>(false), lowLevelDict); int clusterCount = GetCluster(model.allPoints, model.bound, out NativeList <Cluster> boxes, out NativeList <Point> points, voxelCount); ClusterUtils.CheckPath(PATH_FOLDER); ClusterUtils.CheckPath(resPath.ToString()); ClusterUtils.WriteBytes(resPath + PATH_VERTEX + sceneName, points); ClusterUtils.WriteBytes(resPath + PATH_CLUSTER + sceneName, boxes); AddSceneStreaming(model.vm, clusterCount); SaveAsGameScene(); }
/// <summary> /// Calculates previous center position of one of the clusters. /// </summary> /// <param name="id"> Cluster id. Either <see cref="CLUSTER1"/> or <see cref="CLUSTER2"/>. </param> /// <returns> Cluster's centroid previous position or <see cref="TouchManager.INVALID_POSITION"/> if cluster contains no pointers. </returns> public Vector2 GetPreviousCenterPosition(int id) { if (!HasClusters) { return(TouchManager.INVALID_POSITION); } Vector2 result; switch (id) { case CLUSTER1: result = ClusterUtils.GetPrevious2DCenterPosition(cluster1); break; case CLUSTER2: result = ClusterUtils.GetPrevious2DCenterPosition(cluster2); break; default: return(TouchManager.INVALID_POSITION); } return(result); }
internal void INTERNAL_TouchEnded(TouchPoint touch) { var total = numTouches - 1; touchesNumState = TouchesNumState.InRange; if (minTouches <= 0) { // have no touches if (total == 0) { touchesNumState = TouchesNumState.PassedMinThreshold; } } else { if (numTouches >= minTouches) { // had >= minTouches, got < minTouches if (total < minTouches) { touchesNumState = TouchesNumState.PassedMinThreshold; } } // last event we already were under minTouches else { touchesNumState = TouchesNumState.TooFew; } } if (maxTouches > 0) { if (numTouches > maxTouches) { if (total <= maxTouches) { // this event we crossed both minTouches and maxTouches if (touchesNumState == TouchesNumState.PassedMinThreshold) { touchesNumState = TouchesNumState.PassedMinMaxThreshold; } // this event we crossed maxTouches else { touchesNumState = TouchesNumState.PassedMaxThreshold; } } // last event we already were over maxTouches else { touchesNumState = TouchesNumState.TooMany; } } } activeTouches.Remove(touch); numTouches = total; if (combineTouches) { touchSequence.Add(touch); if (NumTouches == 0) { // Checking which points were removed in clusterExistenceTime seconds to set their centroid as cached screen position var cluster = touchSequence.FindElementsLaterThan(Time.time - combineTouchesInterval, shouldCacheTouchPosition); cachedScreenPosition = ClusterUtils.Get2DCenterPosition(cluster); cachedPreviousScreenPosition = ClusterUtils.GetPrevious2DCenterPosition(cluster); } } else { if (NumTouches == 0) { if (shouldCacheTouchPosition(touch)) { cachedScreenPosition = touch.Position; cachedPreviousScreenPosition = touch.PreviousPosition; } else { cachedScreenPosition = TouchManager.INVALID_POSITION; cachedPreviousScreenPosition = TouchManager.INVALID_POSITION; } } } touchEnded(touch); }
/// <inheritdoc /> protected override Vector2 getPointPreviousScreenPosition() { return(ClusterUtils.GetPrevious2DCenterPosition(activeTouches)); }
private void distributePoints() { cluster1.Clear(); cluster2.Clear(); hasClusters = checkClusters(); if (!hasClusters) { return; } cluster1.Add(points[0]); cluster2.Add(points[1]); var total = points.Count; if (total == 2) { return; } var oldHash1 = ""; var oldHash2 = ""; var hash1 = "#"; var hash2 = "#"; while (oldHash1 != hash1 || oldHash2 != hash2) { var center1 = ClusterUtils.Get2DCenterPosition(cluster1); var center2 = ClusterUtils.Get2DCenterPosition(cluster2); Pointer obj1 = null; Pointer obj2 = null; // Take most distant points from cluster1 and cluster2 var maxDist1 = -float.MaxValue; var maxDist2 = -float.MaxValue; for (var i = 0; i < total; i++) { var obj = points[i]; var dist = (center1 - obj.Position).sqrMagnitude; if (dist > maxDist2) { maxDist2 = dist; obj2 = obj; } dist = (center2 - obj.Position).sqrMagnitude; if (dist > maxDist1) { maxDist1 = dist; obj1 = obj; } } // If it is the same point it means that this point is too far away from both clusters and has to be in a separate cluster if (obj1 == obj2) { center1 = (center1 + center2) * .5f; center2 = obj2.Position; } else { center1 = obj1.Position; center2 = obj2.Position; } cluster1.Clear(); cluster2.Clear(); for (var i = 0; i < total; i++) { var obj = points[i]; if ((center1 - obj.Position).sqrMagnitude < (center2 - obj.Position).sqrMagnitude) { cluster1.Add(obj); } else { cluster2.Add(obj); } } oldHash1 = hash1; oldHash2 = hash2; hash1 = ClusterUtils.GetPointsHash(cluster1); hash2 = ClusterUtils.GetPointsHash(cluster2); } markClean(); }
private void RenderStaticShadowmaps() { int shadowWidth = m_staticShadowMapResolution.value.vector2IntValue.x; int shadowHeight = m_staticShadowMapResolution.value.vector2IntValue.y; RenderTexture staticShadowmap = new RenderTexture(shadowWidth, shadowHeight, 32, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear); //staticShadowmap.hideFlags = HideFlags.DontSaveInEditor | HideFlags.DontSaveInBuild; staticShadowmap.dimension = TextureDimension.Tex2D; staticShadowmap.filterMode = FilterMode.Bilinear; staticShadowmap.useMipMap = false; staticShadowmap.name = "StaticShadowmap"; staticShadowmap.Create(); var shadowCameraObj = new GameObject("Shadow Map Camera"); shadowCameraObj.hideFlags = HideFlags.HideAndDontSave; var shadowCamera = shadowCameraObj.AddComponent <Camera>(); var additionalCameraData = shadowCameraObj.AddComponent <AdditionalCameraData>(); additionalCameraData.m_RenderingType = AdditionalCameraData.RenderingType.StaticShadow; additionalCameraData.UpdateCamera(); shadowCamera.enabled = false; shadowCamera.renderingPath = RenderingPath.Forward; shadowCamera.nearClipPlane = 0.1f; shadowCamera.farClipPlane = 100.0f; shadowCamera.depthTextureMode = DepthTextureMode.None; shadowCamera.clearFlags = CameraClearFlags.SolidColor | CameraClearFlags.Depth; shadowCamera.backgroundColor = Color.black; shadowCamera.orthographic = false; shadowCamera.hideFlags = HideFlags.HideAndDontSave; shadowCamera.allowMSAA = false; shadowCamera.stereoTargetEye = StereoTargetEyeMask.None; shadowCameraObj.SetActive(false); //shadowCamera.clearFlags = CameraClearFlags.Depth; shadowCamera.cullingMask = 0; //shadowCamera.RenderWithShader(depthShader, "DO_NOT_RENDER"); shadowCamera.clearFlags = CameraClearFlags.SolidColor; shadowCamera.cullingMask = ~0; for (int i = 0; i < allCachedShadowInfos.Count; i++) { var csd = allCachedShadows[csdIndex[i]]; csd.cachedShadowInfo.Clear(); var info = allCachedShadowInfos[i]; Light l = csd.GetComponent <Light>(); if (l != null && l.shadows != LightShadows.None && (csd.shadowUpdateType == ShadowUpdateType.Static || (l.type == LightType.Directional && csd.UseStaticShadowmapForLastCascade))) { switch (l.type) { case LightType.Directional: Vector3 lightPos = l.transform.position; Vector3 offset = l.transform.localScale / 2.0f; Vector3[] cornerPos = new Vector3[8]; cornerPos[0] = lightPos + offset; cornerPos[1] = lightPos + new Vector3(offset.x * -1.0f, offset.y * 1.0f, offset.z * 1.0f); cornerPos[2] = lightPos + new Vector3(offset.x * 1.0f, offset.y * -1.0f, offset.z * 1.0f); cornerPos[3] = lightPos + new Vector3(offset.x * 1.0f, offset.y * 1.0f, offset.z * -1.0f); cornerPos[4] = lightPos + new Vector3(offset.x * -1.0f, offset.y * -1.0f, offset.z * 1.0f); cornerPos[5] = lightPos + new Vector3(offset.x * -1.0f, offset.y * 1.0f, offset.z * -1.0f); cornerPos[6] = lightPos + new Vector3(offset.x * 1.0f, offset.y * -1.0f, offset.z * -1.0f); cornerPos[7] = lightPos - offset; Bounds lightSpaceBound = new Bounds(); Transform trans = l.transform; trans.localScale = new Vector3(1.0f, 1.0f, 1.0f); for (int j = 0; j < 8; j++) { //Vector3 lightSpacePos = targetLight.transform.worldToLocalMatrix.MultiplyPoint(cornerPos[i]); Vector3 lightSpacePos = trans.InverseTransformPoint(cornerPos[j]); lightSpaceBound.Encapsulate(lightSpacePos); } Vector3 size = lightSpaceBound.extents; Vector3 shadowCamPos = l.transform.localToWorldMatrix.MultiplyPoint(lightSpaceBound.center); trans.localScale = offset * 2.0f; shadowCamPos -= l.transform.forward * size.z; float shadowCamSize = Mathf.Max(size.x, size.y); shadowCamera.aspect = 1.0f; shadowCamera.orthographic = true; shadowCamera.nearClipPlane = 0.1f; shadowCamera.farClipPlane = size.z * 2.0f; shadowCamera.transform.position = shadowCamPos; //targetLight.transform.position;// m_light.transform.position; shadowCamera.transform.rotation = l.transform.rotation; shadowCamera.orthographicSize = shadowCamSize; shadowCamera.targetTexture = staticShadowmap; shadowCamera.pixelRect = info.viewport; info.cullingSphereSize = Mathf.Max(shadowCamSize, size.z); info.view = shadowCamera.worldToCameraMatrix; info.proj = shadowCamera.projectionMatrix; allCachedShadowInfos[i] = info; csd.cachedShadowInfo.Add(info); shadowCamera.Render(); break; case LightType.Spot: shadowCamera.aspect = 1.0f; shadowCamera.orthographic = false; shadowCamera.nearClipPlane = l.shadowNearPlane; shadowCamera.farClipPlane = l.range; shadowCamera.transform.position = l.transform.position; shadowCamera.transform.rotation = l.transform.rotation; shadowCamera.fieldOfView = l.spotAngle; shadowCamera.targetTexture = staticShadowmap; shadowCamera.pixelRect = info.viewport; info.view = shadowCamera.worldToCameraMatrix; info.proj = shadowCamera.projectionMatrix; allCachedShadowInfos[i] = info; csd.cachedShadowInfo.Add(info); shadowCamera.Render(); break; case LightType.Point: break; default: break; } } EditorUtility.SetDirty(csd); EditorSceneManager.MarkSceneDirty(csd.gameObject.scene); } AsyncGPUReadbackRequest shadowmapReadRequest = AsyncGPUReadback.Request(staticShadowmap, 0, TextureFormat.RFloat); shadowmapReadRequest.WaitForCompletion(); float[] shadowmapDatas = shadowmapReadRequest.GetData <float>().ToArray(); Color[] shadowmapColors = new Color[shadowWidth * shadowHeight]; for (int i = 0; i < shadowWidth * shadowHeight; i++) { shadowmapColors[i] = new Color(shadowmapDatas[i], 0.0f, 0.0f, 0.0f); } var shadowMap2D = new Texture2D(shadowWidth, shadowHeight, TextureFormat.RFloat, false); shadowMap2D.SetPixels(shadowmapColors); List <Volume> volumes = ClusterUtils.FindComponentsofType <Volume>(); foreach (Volume vol in volumes) { ClusterShadowSettings settings = null; if (vol.isGlobal && vol.sharedProfile.TryGet <ClusterShadowSettings>(out settings)) { var o = new PropertyFetcher <ClusterShadowSettings>(serializedObject); if (settings == (ClusterShadowSettings)target) { string sceneName = volumes[0].gameObject.scene.name; string scenePath = volumes[0].gameObject.scene.path; int pointIndex = scenePath.LastIndexOf('.'); string sceneDir = scenePath.Remove(pointIndex); bool exist = Directory.Exists(sceneDir); if (!exist) { Directory.CreateDirectory(sceneDir); } String shadowmapPath = sceneDir + "/" + staticShadowmap.name + ".asset"; AssetDatabase.CreateAsset(shadowMap2D, shadowmapPath); m_staticShadowmap.value.objectReferenceValue = AssetDatabase.LoadAssetAtPath(shadowmapPath, typeof(Texture)) as Texture; } } } //if (volumes.Count == 1) //{ // string sceneName = volumes[0].gameObject.scene.name; // string scenePath = volumes[0].gameObject.scene.path; // int pointIndex = scenePath.LastIndexOf('.'); // string sceneDir = scenePath.Remove(pointIndex); // bool exist = Directory.Exists(sceneDir); // if (!exist) // Directory.CreateDirectory(sceneDir); // String shadowmapPath = sceneDir + "/" + staticShadowmap.name + ".asset"; // AssetDatabase.CreateAsset(shadowMap2D, shadowmapPath); // m_staticShadowmap.value.objectReferenceValue = AssetDatabase.LoadAssetAtPath(shadowmapPath, typeof(Texture)) as Texture; //} staticShadowmap.Release(); UnityEngine.Object.DestroyImmediate(additionalCameraData); UnityEngine.Object.DestroyImmediate(shadowCamera); UnityEngine.Object.DestroyImmediate(shadowCameraObj); }
/// <inheritdoc /> protected override Vector2 getPointScreenPosition() { return(ClusterUtils.Get2DCenterPosition(activePointers)); }
private ConfigurationProvider GetConfigurationProvider() { if (this.state.TransactionManager.Settings.IsClustered) { ClusterRegistryConfigurationProvider provider = new ClusterRegistryConfigurationProvider(ClusterUtils.GetTransactionManagerClusterResource(this.state.TransactionManager.Settings.VirtualServerName, this.state.TransactionManager.Settings.ClusterResourceType)); using (provider) { return(provider.OpenKey(@"WSATPrivate\3.0")); } } return(new RegistryConfigurationProvider(Registry.LocalMachine, @"Software\Microsoft\WSAT\3.0")); }