public override void OnPreviewGUI(Rect r, GUIStyle background) { m_previewRenderUtility.BeginPreview(r, background); var target = m_target.Head; if (target != null) { #if UNITY_2017_1_OR_NEWER SetPreviewCamera( m_previewRenderUtility.camera, target.position + new Vector3(0, 0.1f, 0), target.forward ); foreach (var x in m_items) { var mesh = x.Baked(); for (int i = 0; i < x.Materials.Length; ++i) { m_previewRenderUtility.DrawMesh(mesh, x.Transform.position, x.Transform.rotation, x.Materials[i], i); } } m_previewRenderUtility.Render(); #else SetPreviewCamera( m_previewRenderUtility.m_Camera, target.position + new Vector3(0, 0.1f, 0), target.forward ); m_previewRenderUtility.m_Camera.Render(); #endif } m_previewRenderUtility.EndAndDrawPreview(r); }
public Texture DrawRenderPreview(Rect size, Mesh mesh, Material material) { if (previewRenderer == null) { previewRenderer = new PreviewRenderUtility(); previewRenderer.cameraFieldOfView = 15.0f; previewRenderer.ambientColor = (Color.white * 0.6f); previewRenderer.camera.transform.position = (Vector3.forward * 5.0f) + (Vector3.up * 5.0f) + (Vector3.right * 5.0f); previewRenderer.camera.transform.LookAt(Vector3.zero, Vector3.up); previewRenderer.camera.nearClipPlane = 0.01f; previewRenderer.camera.farClipPlane = 50.0f; previewRenderer.lights[0].enabled = true; previewRenderer.lights[0].type = LightType.Directional; previewRenderer.lights[0].color = Color.white; previewRenderer.lights[0].intensity = 1.5f; previewRenderer.lights[0].transform.rotation = Quaternion.Euler(30f, 0f, 0f); previewRenderer.lights[1].enabled = true; previewRenderer.lights[1].intensity = 0.5f; } // Create a duplicate material with NO_CURVE enabled for rendering the preview Material previewMaterial = Instantiate(material); previewMaterial.EnableKeyword("NO_CURVE"); previewRenderer.BeginStaticPreview(size); previewRenderer.DrawMesh(mesh, Matrix4x4.identity, previewMaterial, 0); previewRenderer.Render(); return(previewRenderer.EndStaticPreview()); }
private void DrawRenderPreview(Rect previewRect) { if (selectedMaterial) { previewMaterial.mainTexture = selectedMaterial.mainTexture; if (selectedMaterial.HasProperty("_Color")) { previewMaterial.color = selectedMaterial.GetColor("_Color"); } } Quaternion rotation = Quaternion.Euler(previewRotationX, previewRotationY, 0); Matrix4x4 matrix = Matrix4x4.identity; matrix.SetTRS(Vector3.zero, rotation, Vector3.one); Vector3 position = -matrix.MultiplyPoint(previewMesh.bounds.center); float dist = previewMesh.bounds.extents.magnitude * 2; preview.camera.transform.position = new Vector3(0, 0, -dist); preview.camera.transform.LookAt(Vector3.zero); preview.camera.clearFlags = CameraClearFlags.Color; preview.camera.backgroundColor = Color.gray; preview.camera.fieldOfView = 60; preview.camera.nearClipPlane = .3f; preview.camera.farClipPlane = 1000f; preview.BeginPreview(previewRect, GUIStyle.none); preview.DrawMesh(previewMesh, position, rotation, previewMaterial, 0); preview.Render(); preview.EndAndDrawPreview(previewRect); }
public override void OnPreviewGUI(Rect r, GUIStyle background) { if (!SystemInfo.supportsCubemapArrayTextures || (m_Material != null && !m_Material.shader.isSupported)) { if (Event.current.type == EventType.Repaint) { EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40), "Cubemap array preview is not supported"); } return; } CubemapArray t = (CubemapArray)target; m_Material.mainTexture = t; m_PreviewUtility.BeginPreview(r, background); const float previewDistance = 6.0f; m_PreviewDir = PreviewGUI.Drag2D(m_PreviewDir, r); m_PreviewUtility.camera.transform.position = -Vector3.forward * previewDistance; m_PreviewUtility.camera.transform.rotation = Quaternion.identity; Quaternion rot = Quaternion.Euler(m_PreviewDir.y, 0, 0) * Quaternion.Euler(0, m_PreviewDir.x, 0); m_PreviewUtility.DrawMesh(m_Mesh, Vector3.zero, rot, m_Material, 0); m_PreviewUtility.Render(); Texture renderedTexture = m_PreviewUtility.EndPreview(); GUI.DrawTexture(r, renderedTexture, ScaleMode.StretchToFill, false); EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10, r.width, 30), "Slice " + m_Slice + "\nMip " + m_Mip); }
private void DrawWindow() { Vector2 size = _window.position.size; _previewWindow = new Rect((size.x) - PREVIEW_WINDOW.x - 5, (size.y) - PREVIEW_WINDOW.y - 5, PREVIEW_WINDOW.x, PREVIEW_WINDOW.y); _renderUtils.BeginPreview(_previewWindow, EditorStyles.helpBox); _renderUtils.Render(); _renderUtils.EndAndDrawPreview(_previewWindow); }
private void OnGUI() { Init(); EditorGUIUtility.labelWidth = 50; Rect previewRect = new Rect(0, 0, position.width, position.height / 2); EditorGUI.BeginChangeCheck(); _previewDir = Drag2D(_previewDir, previewRect); if (EditorGUI.EndChangeCheck()) { _eulerAngles.x = Gyro.SignedAngle(Gyro.UnsignedAngle(_previewDir.y % 360)); _eulerAngles.z = Gyro.SignedAngle(Gyro.UnsignedAngle(_previewDir.x % 360)); } else { _eulerAngles.x = Gyro.SignedAngle(EditorGUI.Slider(new Rect(0, previewRect.height, position.width, 20), "Pitch", Gyro.SignedAngle(_eulerAngles.x), -180f, 180)); _eulerAngles.z = Gyro.SignedAngle(EditorGUI.Slider( new Rect(0, previewRect.height + position.height / 10, position.width, 20), "Roll", Gyro.SignedAngle(_eulerAngles.z), -180f, 180)); _eulerAngles.y = Gyro.SignedAngle(EditorGUI.Slider( new Rect(0, previewRect.height + 2 * position.height / 10, position.width, 20), "Yaw", Gyro.SignedAngle(_eulerAngles.y), -180f, 180)); } if (GUI.Button(new Rect(0, previewRect.height + 4 * position.height / 10, position.width, 20), "Reset")) { _eulerAngles = Vector3.zero; _previewDir = Vector2.zero; } _proxy.transform.eulerAngles = _eulerAngles; _preview.BeginPreview(previewRect, GUIStyle.none); Bounds bounds = _proxyFilter.sharedMesh.bounds; float halfSize = bounds.extents.magnitude; float distance = halfSize * 7f; _preview.camera.transform.position = Vector3.up * distance; _preview.camera.nearClipPlane = distance - halfSize * 1.1f; _preview.camera.farClipPlane = distance + halfSize * 1.1f; _preview.camera.transform.eulerAngles = Vector3.right * 90; _preview.lights[0].intensity = 1.4f; _preview.lights[0].transform.rotation = Quaternion.Euler(90, 0, 0); _preview.ambientColor = Color.black; //_preview.DrawMesh(_proxyFilter.sharedMesh, _proxyTransform.position, _proxyTransform.rotation, _proxyRenderer.sharedMaterial, 0); _preview.Render(); _preview.EndAndDrawPreview(previewRect); Gyro.VirtualTilt = Quaternion.Euler(Gyro.UnsignedAngle(-_eulerAngles.x), Gyro.UnsignedAngle(-_eulerAngles.z), _eulerAngles.y); EditorGUI.LabelField(new Rect(0, previewRect.height + 3 * position.height / 10, position.width, 20), "Attitude: " + Gyro.VirtualTilt); }
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) { preview.BeginPreview(r, background); preview.DrawMesh(generator.targetMesh, Matrix4x4.identity, previewMaterial, 0); preview.camera.transform.SetPositionAndRotation(Vector3.forward * -5, Quaternion.identity); preview.Render(); Texture texture = preview.EndPreview(); GUI.DrawTexture(r, texture, ScaleMode.StretchToFill, true); }
protected virtual void DrawWindow() { _rect.width = PREVIEW_WINDOW.x; _rect.height = PREVIEW_WINDOW.y; _rect.x += 5; _renderUtils.BeginPreview(_rect, EditorStyles.helpBox); _renderUtils.Render(); _renderUtils.EndAndDrawPreview(_rect); NextLine(); }
public static byte[] GeneratePrefabThumbnail(GameObject prefab) { var prefabInstance = UnityObject.Instantiate(prefab); var renderUtility = new PreviewRenderUtility(); var renderCamera = renderUtility.camera; var renderCameraTransform = renderCamera.transform; renderCamera.fieldOfView = k_FieldOfView; renderUtility.AddSingleGO(prefabInstance); renderCamera.backgroundColor = k_BackgroundColor; var prefabList = new List <GameObject>(); prefabList.Add(prefabInstance); var bounds = BoundsUtils.GetBounds(prefabList); var halfSize = Mathf.Max(bounds.extents.magnitude, 0.0001f); var distance = halfSize * k_CameraDistanceRatio; var pos = bounds.center - k_PreviewRotation * (Vector3.forward * distance); renderCameraTransform.position = pos; renderCameraTransform.rotation = k_PreviewRotation; renderCamera.nearClipPlane = distance - halfSize * k_Padding; renderCamera.farClipPlane = distance + halfSize * k_Padding; renderUtility.lights[0].intensity = k_LightIntensity; renderUtility.lights[0].transform.rotation = k_FirstLightRotation; renderUtility.lights[1].intensity = k_LightIntensity; renderUtility.lights[1].transform.rotation = k_SecondLightRotation; renderUtility.ambientColor = k_AmbientLightColor; renderUtility.BeginPreview(k_TextureRect, null); renderUtility.Render(true); var renderTexture = renderUtility.EndPreview() as RenderTexture; var temporary = RenderTexture.GetTemporary((int)k_TextureRect.width, (int)k_TextureRect.height, 0, GraphicsFormat.R8G8B8A8_UNorm); Graphics.Blit(renderTexture, temporary); RenderTexture.active = temporary; var texture = new Texture2D((int)k_TextureRect.width, (int)k_TextureRect.height, TextureFormat.RGBA32, false, false); texture.ReadPixels(new Rect(0.0f, 0.0f, k_TextureRect.width, k_TextureRect.height), 0, 0); texture.Apply(); var thumbnail = texture.EncodeToPNG(); RenderTexture.ReleaseTemporary(temporary); renderUtility.Cleanup(); UnityObject.DestroyImmediate(texture); return(thumbnail); }
public override void OnPreviewGUI(Rect r, GUIStyle background) { if (!ShaderUtil.hardwareSupportsRectRenderTexture || !SystemInfo.supports3DTextures) { if (Event.current.type == EventType.Repaint) { EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40), "3D texture preview not supported"); } return; } m_PreviewDir = Drag2D(m_PreviewDir, r); Event e = Event.current; if (e.type == EventType.ScrollWheel) { zoom = Mathf.Clamp(zoom + e.delta.y * 0.1f, 0.05f, 5f); m_PreviewUtility.camera.nearClipPlane = Mathf.Lerp(0.05f, 2, Mathf.InverseLerp(0.05f, 3f, zoom)); e.Use(); Repaint(); } if (e.type != EventType.Repaint) { return; } InitPreview(); material3D.mainTexture = target as Texture3D; m_PreviewUtility.BeginPreview(r, background); bool oldFog = RenderSettings.fog; Unsupported.SetRenderSettingsUseFogNoDirty(false); var cameraTransform = m_PreviewUtility.camera.transform; cameraTransform.position = -Vector3.forward * zoom; cameraTransform.rotation = Quaternion.identity; Quaternion rot = Quaternion.Euler(m_PreviewDir.y, 0, 0) * Quaternion.Euler(0, m_PreviewDir.x, 0); m_PreviewUtility.DrawMesh(Mesh, Vector3.zero, rot, material3D, 0); m_PreviewUtility.Render(); Unsupported.SetRenderSettingsUseFogNoDirty(oldFog); m_PreviewUtility.EndAndDrawPreview(r); if (continuousRepaint) { Repaint(); } }
protected Texture EndPreview(PreviewRenderUtility util) { util.Render(true); UnityEditorInternal.InternalEditorUtility.RemoveCustomLighting(); Unsupported.SetRenderSettingsUseFogNoDirty(fog); var texture = util.EndPreview(); return(texture); }
public void Render(Rect rect, Mesh mesh, Material mat = null) { if (e.type == EventType.Repaint) { previewUtility.BeginPreview(rect, GUIStyle.none); { previewUtility.DrawMesh(mesh, Vector3.zero, Quaternion.identity, mat, 0); previewUtility.Render(true, true); } previewUtility.EndAndDrawPreview(rect); } }
public override void OnInteractivePreviewGUI(Rect rect, GUIStyle background) { if (!graph || !graph.Prefab) { return; } if (graph.isPlaying) { deltaTime = (float)EditorApplication.timeSinceStartup; } if (previewObject == null || lastPreviewHash != graph.Prefab.GetHashCode()) { Cleanup(); CreateRenderer(); lastPreviewHash = graph.Prefab.GetHashCode(); previewObject = previewRenderUtility.InstantiatePrefabInScene(graph.Prefab); goHeight = GetHeight(previewObject.transform); } DrawRuntimeFields(); if (graph.isPlaying) { var clip = graph.Evaluate(deltaTime); if (clip != null) { clip.SampleAnimation(graph.Prefab, graph.internalCounter); RepaintGraph(); } } previewRenderUtility.BeginPreview(rect, background); foreach (var light in previewRenderUtility.lights) { light.transform.rotation = previewCamera.transform.rotation; } previewRenderUtility.Render(); previewCamera.Render(); previewRenderUtility.EndAndDrawPreview(rect); if (Event.current.type == EventType.Repaint) { previewRect = rect; } // http://anchan828.github.io/editor-manual/web/customeditor.html // http://anchan828.github.io/editor-manual/web/spriteanimationpreview2.html UpdatePosition(); PreviewEventListeners(); }
// Render a mesh in preview with wireframe material. private void RenderMeshPreviewSkipCameraAndLightingWireframe( Mesh cMeshWire, Bounds cBounds, PreviewRenderUtility cPreviewUtility, Material cWireMaterial, MaterialPropertyBlock cCustomProperties, Vector2 vDirection, int nMeshSubset // -1 for whole mesh. ) { if ((null == cMeshWire) || (null == cPreviewUtility)) { return; } Quaternion cRot = Quaternion.Euler(vDirection.y, 0, 0) * Quaternion.Euler(0, vDirection.x, 0); Vector3 vPos = cRot * (-cBounds.center); bool bOldFog = RenderSettings.fog; Unsupported.SetRenderSettingsUseFogNoDirty(false); int submeshes = cMeshWire.subMeshCount; if (null != cWireMaterial) { cPreviewUtility.camera.clearFlags = CameraClearFlags.Nothing; GL.wireframe = true; if ((nMeshSubset < 0) || (nMeshSubset >= submeshes)) { for (int i = 0; i < submeshes; ++i) { cPreviewUtility.DrawMesh(cMeshWire, vPos, cRot, cWireMaterial, i, cCustomProperties); } } else { cPreviewUtility.DrawMesh(cMeshWire, vPos, cRot, cWireMaterial, nMeshSubset, cCustomProperties); } cPreviewUtility.Render(); GL.wireframe = false; } Unsupported.SetRenderSettingsUseFogNoDirty(bOldFog); }
virtual protected void OnDrawModel() { if (m_Preview == null) { return; } //other mesh //model SetEnabledRecursive(true); #if UNITY_2017_1_OR_NEWER m_Preview.Render(); #else m_Preview.camera.Render(); #endif SetEnabledRecursive(false); }
static Texture GetPreviewTexture(PreviewRenderUtility previewUtility, Vector2 previewDir, Rect region, Material material) { if (styles == null) { styles = new Styles(); } var background = styles.background; var mesh = GetPreviewSphere(); var camera = previewUtility.camera; var bounds = mesh.bounds; var halfSize = bounds.extents.magnitude; var distance = 2.5f * halfSize; camera.transform.position = -Vector3.forward * distance; camera.transform.rotation = Quaternion.identity; camera.nearClipPlane = distance - halfSize * 1.1f; camera.farClipPlane = distance + halfSize * 1.1f; camera.fieldOfView = 30.0f; camera.orthographicSize = 1.0f; camera.clearFlags = CameraClearFlags.Nothing; previewUtility.lights[0].intensity = 1.0f; previewUtility.lights[0].transform.rotation = Quaternion.Euler(40f, 40f, 0); previewUtility.lights[1].intensity = 1.0f; previewUtility.BeginStaticPreview(region); var fog = RenderSettings.fog; Unsupported.SetRenderSettingsUseFogNoDirty(false); camera.Render(); Unsupported.SetRenderSettingsUseFogNoDirty(fog); var rot = Quaternion.Euler(previewDir.y, 0, 0) * Quaternion.Euler(0, previewDir.x, 0); var pos = rot * (-bounds.center); previewUtility.DrawMesh(mesh, pos, rot, material, 0); previewUtility.Render(false, false); return(previewUtility.EndStaticPreview()); }
Texture2D GetPreviewTexture(GameObject go, int width, int height) { if (renderUtility == null) { InitializePreviewRenderUtility(); } var rect = new Rect(0, 0, width, height); renderUtility.BeginStaticPreview(rect); MeshFilter[] meshFilters = go.GetComponentsInChildren <MeshFilter>(); MeshRenderer[] meshRenderers = go.GetComponentsInChildren <MeshRenderer>(); for (int i = 0; i < meshRenderers.Length; i++) { bound.Encapsulate(meshRenderers[i].bounds); renderUtility.DrawMesh(meshFilters[i].sharedMesh, Matrix4x4.identity, meshRenderers[i].sharedMaterials[0], 0); } float magnitude = bound.extents.magnitude; float num = magnitude * rangeFactor; var quaternion = Quaternion.Euler(-rotation.y, -rotation.x, 0f); var position = bound.center - quaternion * (Vector3.forward * num); renderUtility.camera.transform.position = position; renderUtility.camera.transform.rotation = quaternion; renderUtility.camera.nearClipPlane = num - magnitude * 1.1f; renderUtility.camera.farClipPlane = num + magnitude * 1.1f; //renderUtility.lights[0].transform.rotation = Quaternion.Euler(40f, 40f, 0f); renderUtility.lights[0].transform.rotation = renderUtility.camera.transform.rotation; //renderUtility.lights[1].intensity = 2.0f; renderUtility.Render(true); Texture2D result = renderUtility.EndStaticPreview(); renderUtility.Cleanup(); return(result); }
public override void DrawPreview(Rect rect) { //process preview controls ProcessPreviewInput(rect); //update display flags UpdateDisplayFlags(); if (_update_mesh) { //update mesh UpdateMesh(); //clear update mesh flag _update_mesh = false; } if (_render_mesh) { UpdateDisplay(); //update preview render texture _previewutility.BeginPreview(rect, GUI.skin.GetStyle("DarkGrey")); //draw axi stuff _display.DrawDisplayObjects(_previewutility); //draw mesh if (_mesh.triangles.Length > 0 && mesh_mat != null) { _previewutility.DrawMesh(_mesh, Vector3.zero, Quaternion.identity, mesh_mat, 0); } //draw vertices DrawVertex(); //render preview scene _previewutility.Render(); _render = _previewutility.EndPreview(); //clear render mesh flag _render_mesh = false; } //return if nothing to draw if (_render == null) { return; } //draw preview render texture GUI.DrawTexture(rect, _render); rect = VxlGUI.GetPaddedRect(rect, VxlGUI.MED_PAD); _display.DrawGUI(new Rect(rect.x, rect.y, 0.5f * rect.width, 0.5f * rect.height)); }
private void OnGUI() { GUILayout.Label("Settings"); sub = EditorGUILayout.IntSlider("Subdivison Depth", sub, 0, 5); bool g = GUILayout.Button("Generate"); bool b = GUILayout.Button("Save"); Rect r = new Rect(0, 0, 512, 512); if (mat == null) { mat = Resources.Load <Material>("_Game/Materials/PlanetSurface"); } if (prev == null) { prev = new PreviewRenderUtility(); } if (g) { // SphereMesh sm = new SphereMesh(sub); // m = sm.Mesh; } if (m != null && mat != null && prev != null) { prev.camera.transform.position = -Vector3.forward * 5; prev.camera.transform.rotation = Quaternion.identity; prev.BeginPreview(r, GUIStyle.none); prev.DrawMesh(m, Vector3.zero, Quaternion.identity, mat, 0); prev.Render(); GUI.DrawTexture(r, prev.EndPreview()); } if (b) { SaveMesh(); } }
private void RenderIcon(PreviewRenderUtility previewRenderer, Target target) { const int w = 1024; const int h = 1024; var rect = new Rect(0f, 0f, w, h); previewRenderer.BeginPreview(rect, null); previewRenderer.InstantiatePrefabInScene(_prefab); previewRenderer.camera.clearFlags = CameraClearFlags.SolidColor; previewRenderer.camera.backgroundColor = target.Background; previewRenderer.camera.transform.position = _cameraSettings.Position; previewRenderer.camera.transform.rotation = Quaternion.Euler(_cameraSettings.Rotation); previewRenderer.camera.nearClipPlane = _cameraSettings.Near; previewRenderer.camera.farClipPlane = _cameraSettings.Far; previewRenderer.Render(true); var rt = previewRenderer.EndPreview(); var temporary = RenderTexture.GetTemporary(w, h, 0, GraphicsFormat.R8G8B8A8_UNorm); Graphics.Blit(rt, temporary, _tex2rgbMaterial); RenderTexture.active = temporary; var texture = new Texture2D(w, h, TextureFormat.RGBA32, false, false); texture.ReadPixels(rect, 0, 0); texture.Apply(); RenderTexture.ReleaseTemporary(temporary); try { var path = AssetDatabase.GetAssetPath(target.TargetTexture); File.WriteAllBytes(path, texture.EncodeToPNG()); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); } catch (Exception e) { Debug.LogError($"Unable to write to icon: {e.Message}"); } }
private static void DrawLayerPreview(Rect position, [NotNull] PreviewRenderUtility preview, [NotNull] LayerPreviewRenderer renderer, [NotNull] Texture2D mask, Vector2 inputRange, Vector2 outputRange, Vector4 weights) { if (position.width <= 0 || position.height <= 0) { return; } var aspect = position.width / position.height; const float extent = 1.4f; #if UNITY_2017_1_OR_NEWER var camera = preview.camera; #else var camera = preview.m_Camera; #endif camera.projectionMatrix = Matrix4x4.Ortho(-extent, extent, -extent / aspect, extent / aspect, 0, 3); camera.worldToCameraMatrix = Matrix4x4.LookAt(new Vector3(0.25f - 0.25f, 0.25f - 0.25f, -1f), new Vector3(0f - 0.25f, 0 - 0.25f, 0f), Vector3.up); preview.BeginPreview(position, GUIStyle.none); { GL.Clear(true, true, new Color(0.15f, 0.15f, 0.15f, 1)); renderer.Configure(mask, weights, inputRange.x, inputRange.y, outputRange.x, outputRange.y); renderer.Render(preview); #if UNITY_2017_1_OR_NEWER preview.Render(updatefov: false); #else camera.Render(); #endif } var image = preview.EndPreview(); GL.sRGBWrite = QualitySettings.activeColorSpace == ColorSpace.Linear; GUI.DrawTexture(position, image, ScaleMode.StretchToFill, true); GL.sRGBWrite = false; }
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) { if (m_VisualEffectGO == null) { OnEnable(); } bool isRepaint = (Event.current.type == EventType.Repaint); m_Angles = VFXPreviewGUI.Drag2D(m_Angles, r); Renderer renderer = m_VisualEffectGO.GetComponent <Renderer>(); if (renderer == null) { return; } if (renderer.bounds.size != Vector3.zero) { m_CurrentBounds = renderer.bounds; //make sure that none of the bounds values are 0 if (m_CurrentBounds.size.x == 0) { Vector3 size = m_CurrentBounds.size; size.x = (m_CurrentBounds.size.y + m_CurrentBounds.size.z) * 0.1f; m_CurrentBounds.size = size; } if (m_CurrentBounds.size.y == 0) { Vector3 size = m_CurrentBounds.size; size.y = (m_CurrentBounds.size.x + m_CurrentBounds.size.z) * 0.1f; m_CurrentBounds.size = size; } if (m_CurrentBounds.size.z == 0) { Vector3 size = m_CurrentBounds.size; size.z = (m_CurrentBounds.size.x + m_CurrentBounds.size.y) * 0.1f; m_CurrentBounds.size = size; } } if (m_FrameCount == kSafeFrame) // wait to frame before asking the renderer bounds as it is a computed value. { float maxBounds = Mathf.Sqrt(m_CurrentBounds.size.x * m_CurrentBounds.size.x + m_CurrentBounds.size.y * m_CurrentBounds.size.y + m_CurrentBounds.size.z * m_CurrentBounds.size.z); m_Distance = Mathf.Max(0.01f, maxBounds * 1.25f); ComputeFarNear(); } else { ComputeFarNear(); } m_FrameCount++; if (Event.current.isScrollWheel) { m_Distance *= 1 + (Event.current.delta.y * .015f); } if (m_Mat == null) { m_Mat = (Material)EditorGUIUtility.LoadRequired("SceneView/HandleLines.mat"); } if (isRepaint) { m_PreviewUtility.BeginPreview(r, background); Quaternion rot = Quaternion.Euler(0, m_Angles.x, 0) * Quaternion.Euler(m_Angles.y, 0, 0); m_PreviewUtility.camera.transform.position = m_CurrentBounds.center + rot * new Vector3(0, 0, -m_Distance); m_PreviewUtility.camera.transform.localRotation = rot; m_PreviewUtility.DrawMesh(s_CubeWireFrame, Matrix4x4.TRS(m_CurrentBounds.center, Quaternion.identity, m_CurrentBounds.size), m_Mat, 0); m_PreviewUtility.Render(true); m_PreviewUtility.EndAndDrawPreview(r); // Ask for repaint so the effect is animated. Repaint(); } }
public void OnGUI() { Event guiEvent = Event.current; Rect toolRect = EditorGUILayout.BeginVertical(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); UpdateToolbar(guiEvent); // FIXME - I get jitter in the toolbar when the window resizes even if I give it a constant // rectangle here, so just do this as the simplest version. selectedTool = GUILayout.Toolbar(selectedTool, toolbar); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.EndVertical(); Rect viewRect = new Rect(0, toolRect.yMax, this.position.width, this.position.height - toolRect.yMax); activeViewTool = ViewTool.None; if (guiEvent.isScrollWheel) { activeViewTool = ViewTool.Zoom; } if (guiEvent.alt) { if (guiEvent.control) { activeViewTool = ViewTool.Zoom; } else { activeViewTool = ViewTool.Pan; } } MouseCursor activeCursor = MouseCursor.Arrow; switch (activeViewTool) { case ViewTool.Zoom: activeCursor = MouseCursor.Zoom; break; case ViewTool.Pan: activeCursor = MouseCursor.Pan; break; } EditorGUIUtility.AddCursorRect(viewRect, activeCursor); bool handled = false; if (guiEvent.type == EventType.Repaint) { //GUILayout.BeginArea(toolbarRect); //selectedTool = GUILayout.Toolbar(selectedTool, toolbar); //GUILayout.BeginHorizontal(); //GUILayout.Toolbar(0, images, EditorStyles.toolbarButton); //GUILayout.EndHorizontal(); //GUILayout.EndArea(); renderUtil.BeginPreview(viewRect, GUIStyle.none); // renderUtil.camera.backgroundColor is reset in BeginPreview() renderUtil.camera.backgroundColor = backgroundColor; foreach (VectorShape shape in shapes) { renderUtil.DrawMesh(shape.ShapeMesh, Matrix4x4.identity, renderMaterial, 0); } renderUtil.Render(); Handles.SetCamera(renderUtil.camera); VectorShape.handleDrawSize = HandleUtility.GetHandleSize(Vector3.zero) * viewRect.height / viewRect.width; foreach (VectorShape selected in selection) { selected.DrawEditorHandles(true); } renderUtil.EndAndDrawPreview(viewRect); } else if (guiEvent.isScrollWheel && (EditorWindow.mouseOverWindow == this)) { float zoomFactor = HandleUtility.niceMouseDeltaZoom; renderUtil.camera.orthographicSize *= (1 - zoomFactor * .02f); handled = true; } else if (guiEvent.isMouse) { Camera camera = renderUtil.camera; float viewScale = camera.orthographicSize * 2f / viewRect.height; if (activeViewTool == ViewTool.Pan) { camera.transform.position += (Vector3)(guiEvent.delta * new Vector2(-viewScale, viewScale)); handled = true; } else if (activeViewTool == ViewTool.Zoom) { float zoomFactor = HandleUtility.niceMouseDeltaZoom; renderUtil.camera.orthographicSize *= (1 + zoomFactor * .005f); handled = true; } if (!handled) { // Convert the event to shape space for convenience Vector2 mousePosition = guiEvent.mousePosition; Vector2 delta = guiEvent.delta; Vector2 cameraPos = camera.transform.position; Vector2 viewPos = mousePosition - viewRect.center; guiEvent.mousePosition = new Vector2( viewPos.x * viewScale + cameraPos.x, viewPos.y * -viewScale + cameraPos.y ); guiEvent.delta = guiEvent.delta * new Vector2(viewScale, -viewScale); foreach (VectorShape selected in selection) { handled |= selected.HandleEditorEvent(guiEvent, true); } guiEvent.mousePosition = mousePosition; guiEvent.delta = delta; } } else if (guiEvent.type == EventType.ValidateCommand) { switch (guiEvent.commandName) { case Cmd_Delete: if (selection.Count > 0) { handled = true; } break; case Cmd_SelectAll: if (shapes.Count > 0) { handled = true; } break; } } else if (guiEvent.type == EventType.ExecuteCommand) { switch (guiEvent.commandName) { case Cmd_Delete: foreach (VectorShape selected in selection) { shapes.Remove(selected); } selection.Clear(); handled = true; break; case Cmd_SelectAll: foreach (VectorShape selected in shapes) { selection.Add(selected); } handled = true; break; case Cmd_ModifierKeysChanged: Repaint(); handled = true; break; } } if (handled) { guiEvent.Use(); } }
public void OnGUI() { Event guiEvent = Event.current; activeViewTool = ViewTool.None; if (guiEvent.isScrollWheel) { activeViewTool = ViewTool.Zoom; } else if ((activeTool == ToolSet.View) || (guiEvent.alt)) { if (guiEvent.control) { activeViewTool = ViewTool.Zoom; } else { activeViewTool = ViewTool.Pan; } } if (guiEvent.type == EventType.MouseDown) { mouseDownPosition = guiEvent.mousePosition; mouseDownTime = Time.time; mouseIsDown = true; } else if (guiEvent.type == EventType.MouseUp) { mouseIsDown = false; } Rect toolRect = new Rect(0, 0, this.position.width, toolbarHeight + toolbarPadding * 2); Rect toolbarRect = new Rect(toolbarPadding * 2, toolbarPadding, toolbarWidth * toolIcons.Length, toolbarHeight); OnToolbarArea(guiEvent, toolbarRect); Rect separatorRect = new Rect(toolbarRect.xMax + toolbarPadding, 0, separatorWidth, toolRect.height); GUI.DrawTexture(separatorRect, separatorTexture); Rect infoRect = new Rect(separatorRect.xMax, 0, toolRect.width - separatorRect.xMax, toolRect.height); switch (activeTool) { case ToolSet.View: OnInfoAreaView(guiEvent, infoRect); break; case ToolSet.Select: OnInfoAreaSelect(guiEvent, infoRect); break; case ToolSet.Brush: OnInfoAreaBrush(guiEvent, infoRect); break; case ToolSet.Shape: OnInfoAreaShape(guiEvent, infoRect); break; } Rect viewRect = new Rect(0, toolRect.yMax, this.position.width, this.position.height - toolRect.yMax); MouseCursor activeCursor = MouseCursor.Arrow; switch (activeViewTool) { case ViewTool.Zoom: activeCursor = MouseCursor.Zoom; break; case ViewTool.Pan: activeCursor = MouseCursor.Pan; break; } EditorGUIUtility.AddCursorRect(viewRect, activeCursor); bool handled = false; if (guiEvent.type == EventType.Repaint) { renderUtil.BeginPreview(viewRect, GUIStyle.none); // renderUtil.camera.backgroundColor is reset in BeginPreview() renderUtil.camera.backgroundColor = backgroundColor; foreach (VectorShape shape in shapes) { renderUtil.DrawMesh(shape.ShapeMesh, Matrix4x4.identity, renderMaterial, 0); //Debug.Log(shape.ShapeMesh.vertexCount); } renderUtil.Render(); Handles.SetCamera(renderUtil.camera); VectorShape.handleDrawSize = HandleUtility.GetHandleSize(Vector3.zero) * viewRect.height / viewRect.width; foreach (VectorShape selected in selection) { selected.DrawEditorHandles(true, (selected == focusedShape)); } if (selectionRect != Rect.zero) { Color outlineColor = Handles.color; Color fillColor = new Color(outlineColor.r, outlineColor.g, outlineColor.b, 0.2f); Handles.DrawSolidRectangleWithOutline(selectionRect, fillColor, outlineColor); } renderUtil.EndAndDrawPreview(viewRect); } else if (guiEvent.isScrollWheel && (EditorWindow.mouseOverWindow == this)) { float zoomFactor = HandleUtility.niceMouseDeltaZoom; renderUtil.camera.orthographicSize *= (1 - zoomFactor * .02f); // Update matrix from mouse to shape space mouseToShapeScale = renderUtil.camera.orthographicSize * 2f / viewRect.height; mouseToShapeMatrix = Matrix2D.Translate(renderUtil.camera.transform.position) * Matrix2D.Scale(new Vector2(mouseToShapeScale, -mouseToShapeScale)) * Matrix2D.Translate(-viewRect.center); handled = true; } else if (guiEvent.isMouse) { // Update mouse position and matrix from mouse to shape space mouseToShapeScale = renderUtil.camera.orthographicSize * 2f / viewRect.height; mousePosition = guiEvent.mousePosition; mouseToShapeMatrix = Matrix2D.Translate(renderUtil.camera.transform.position) * Matrix2D.Scale(new Vector2(mouseToShapeScale, -mouseToShapeScale)) * Matrix2D.Translate(-viewRect.center); mouseInContent = (viewRect.Contains(mousePosition)); if (activeViewTool != ViewTool.None) { handled = OnViewToolMouse(guiEvent); } else { switch (activeTool) { case ToolSet.Select: handled = OnSelectToolMouse(guiEvent); break; case ToolSet.Brush: handled = OnBrushToolMouse(guiEvent); break; case ToolSet.Shape: handled = OnShapeToolMouse(guiEvent); break; } } if (!handled) { Vector2 delta = guiEvent.delta; guiEvent.mousePosition = MouseToShapePoint(mousePosition); guiEvent.delta = guiEvent.delta * new Vector2(mouseToShapeScale, -mouseToShapeScale); foreach (VectorShape selected in selection) { handled |= selected.HandleEditorEvent(guiEvent, true); } guiEvent.mousePosition = mousePosition; guiEvent.delta = delta; } } else if (guiEvent.type == EventType.ValidateCommand) { switch (guiEvent.commandName) { case Cmd_Delete: if (selection.Count > 0) { handled = true; } break; case Cmd_SelectAll: if (shapes.Count > 0) { handled = true; } break; } } else if (guiEvent.type == EventType.ExecuteCommand) { switch (guiEvent.commandName) { case Cmd_Delete: foreach (VectorShape selected in selection) { shapes.Remove(selected); } selection.Clear(); handled = true; break; case Cmd_SelectAll: foreach (VectorShape selected in shapes) { selection.Add(selected); } handled = true; break; case Cmd_ModifierKeysChanged: Repaint(); handled = true; break; } } if (handled) { guiEvent.Use(); } }
public void DoRenderPreview(Rect previewRect, GUIStyle background) { var probe = RenderSettings.ambientProbe; previewUtility.BeginPreview(previewRect, background); Quaternion bodyRot; Quaternion rootRot; Vector3 rootPos; Vector3 bodyPos = rootPosition; Vector3 pivotPos; if (Animator && Animator.isHuman) { rootRot = Animator.rootRotation; rootPos = Animator.rootPosition; bodyRot = Animator.bodyRotation; pivotPos = Animator.pivotPosition; } else if (Animator && Animator.hasRootMotion) { rootRot = Animator.rootRotation; rootPos = Animator.rootPosition; bodyRot = Quaternion.identity; pivotPos = Vector3.zero; } else { rootRot = Quaternion.identity; rootPos = Vector3.zero; bodyRot = Quaternion.identity; pivotPos = Vector3.zero; } SetupPreviewLightingAndFx(probe); Vector3 direction = bodyRot * Vector3.forward; direction[1] = 0; Quaternion directionRot = Quaternion.LookRotation(direction); Vector3 directionPos = rootPos; Quaternion pivotRot = rootRot; // Scale all Preview Objects to fit avatar size. PositionPreviewObjects(pivotRot, pivotPos, bodyRot, bodyPosition, directionRot, rootRot, rootPos, directionPos, m_AvatarScale); bool dynamicFloorHeight = is2D ? false : Mathf.Abs(m_NextFloorHeight - m_PrevFloorHeight) > m_ZoomFactor * 0.01f; // Calculate floor height and alpha float mainFloorHeight, mainFloorAlpha; if (dynamicFloorHeight) { float fadeMoment = m_NextFloorHeight < m_PrevFloorHeight ? kFloorFadeDuration : (1 - kFloorFadeDuration); mainFloorHeight = timeControl.normalizedTime < fadeMoment ? m_PrevFloorHeight : m_NextFloorHeight; mainFloorAlpha = Mathf.Clamp01(Mathf.Abs(timeControl.normalizedTime - fadeMoment) / kFloorFadeDuration); } else { mainFloorHeight = m_PrevFloorHeight; mainFloorAlpha = is2D ? 0.5f : 1; } Quaternion floorRot = is2D ? Quaternion.Euler(-90, 0, 0) : Quaternion.identity; Vector3 floorPos = m_ReferenceInstance.transform.position; floorPos.y = mainFloorHeight; // Render shadow map Matrix4x4 shadowMatrix; RenderTexture shadowMap = RenderPreviewShadowmap(previewUtility.lights[0], m_BoundingVolumeScale / 2, bodyPosition, floorPos, out shadowMatrix); float tempZoomFactor = (is2D ? 1.0f : m_ZoomFactor); // Position camera previewUtility.camera.orthographic = is2D; if (is2D) { previewUtility.camera.orthographicSize = 2.0f * m_ZoomFactor; } previewUtility.camera.nearClipPlane = 0.5f * tempZoomFactor; previewUtility.camera.farClipPlane = 100.0f * m_AvatarScale; Quaternion camRot = Quaternion.Euler(-m_PreviewDir.y, -m_PreviewDir.x, 0); // Add panning offset Vector3 camPos = camRot * (Vector3.forward * -5.5f * tempZoomFactor) + bodyPos + m_PivotPositionOffset; previewUtility.camera.transform.position = camPos; previewUtility.camera.transform.rotation = camRot; SetPreviewCharacterEnabled(true, m_ShowReference); previewUtility.Render(m_Option != PreviewPopupOptions.DefaultModel); SetPreviewCharacterEnabled(false, false); // Texture offset - negative in order to compensate the floor movement. Vector2 textureOffset = -new Vector2(floorPos.x, is2D ? floorPos.y : floorPos.z); // Render main floor { Material mat = m_FloorMaterial; Matrix4x4 matrix = Matrix4x4.TRS(floorPos, floorRot, Vector3.one * kFloorScale * m_AvatarScale); mat.mainTextureOffset = textureOffset * kFloorScale * 0.08f * (1.0f / m_AvatarScale); mat.SetTexture("_ShadowTexture", shadowMap); mat.SetMatrix("_ShadowTextureMatrix", shadowMatrix); mat.SetVector("_Alphas", new Vector4(kFloorAlpha * mainFloorAlpha, kFloorShadowAlpha * mainFloorAlpha, 0, 0)); mat.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Background; Graphics.DrawMesh(m_FloorPlane, matrix, mat, ReflectionHelper.Instance.Camera.PreviewCullingLayer, previewUtility.camera, 0); } // Render small floor if (dynamicFloorHeight) { bool topIsNext = m_NextFloorHeight > m_PrevFloorHeight; float floorHeight = topIsNext ? m_NextFloorHeight : m_PrevFloorHeight; float otherFloorHeight = topIsNext ? m_PrevFloorHeight : m_NextFloorHeight; float floorAlpha = (floorHeight == mainFloorHeight ? 1 - mainFloorAlpha : 1) * Mathf.InverseLerp(otherFloorHeight, floorHeight, rootPos.y); floorPos.y = floorHeight; Material mat = m_FloorMaterialSmall; mat.mainTextureOffset = textureOffset * kFloorScaleSmall * 0.08f; mat.SetTexture("_ShadowTexture", shadowMap); mat.SetMatrix("_ShadowTextureMatrix", shadowMatrix); mat.SetVector("_Alphas", new Vector4(kFloorAlpha * floorAlpha, 0, 0, 0)); Matrix4x4 matrix = Matrix4x4.TRS(floorPos, floorRot, Vector3.one * kFloorScaleSmall * m_AvatarScale); Graphics.DrawMesh(m_FloorPlane, matrix, mat, ReflectionHelper.Instance.Camera.PreviewCullingLayer, previewUtility.camera, 0); } var clearMode = previewUtility.camera.clearFlags; previewUtility.camera.clearFlags = CameraClearFlags.Nothing; previewUtility.Render(false); previewUtility.camera.clearFlags = clearMode; RenderTexture.ReleaseTemporary(shadowMap); }
public void OnGUI() { Event guiEvent = Event.current; if (guiEvent.isScrollWheel) { overrideAction = ActionType.ViewZoom; } else if (guiEvent.type == EventType.MouseDown) { mouseDownPosition = guiEvent.mousePosition; mouseDownTime = Time.time; mouseIsDown = true; } else if (guiEvent.type == EventType.MouseUp) { mouseIsDown = false; } else if (guiEvent.type != EventType.Repaint) { overrideAction = ActionType.None; if (guiEvent.alt) { if (guiEvent.control) { overrideAction = ActionType.ViewZoom; } else { overrideAction = ActionType.ViewPan; } } } UpdateMouseToShape(); Rect toolRect = new Rect(0, 0, this.position.width, toolAreaHeight); Rect toolbarRect = new Rect(toolbarPadding * 2, toolbarPadding, toolbarWidth * (toolIcons.Length + 1) + toolbarPadding, toolbarHeight); OnToolbarArea(guiEvent, toolbarRect); Rect separatorRect = new Rect(toolbarRect.xMax + toolbarPadding, 0, separatorWidth, toolRect.height); GUI.DrawTexture(separatorRect, separatorTexture); Rect infoRect = new Rect(separatorRect.xMax, 0, toolRect.width - separatorRect.xMax, toolRect.height); switch (activeTool) { case ToolSet.View: OnInfoAreaView(guiEvent, infoRect); baseAction = ActionType.ViewPan; break; case ToolSet.Select: OnInfoAreaSelect(guiEvent, infoRect); baseAction = ActionType.SelectNormal; break; case ToolSet.Brush: OnInfoAreaBrush(guiEvent, infoRect); baseAction = ActionType.LineEdit; break; case ToolSet.Shape: OnInfoAreaShape(guiEvent, infoRect); baseAction = ActionType.ShapeEdit; break; } Rect viewRect = new Rect(0, toolRect.yMax, this.position.width, this.position.height - toolRect.yMax); MouseCursor activeCursor = MouseCursor.Arrow; switch (action) { case ActionType.ViewPan: activeCursor = MouseCursor.Pan; break; case ActionType.ViewZoom: activeCursor = MouseCursor.Zoom; break; } EditorGUIUtility.AddCursorRect(viewRect, activeCursor); bool handled = false; if (guiEvent.type == EventType.Repaint) { renderUtil.BeginPreview(viewRect, GUIStyle.none); renderUtil.camera.backgroundColor = backgroundColor; foreach (VectorShape shape in shapes) { renderUtil.DrawMesh(shape.ShapeMesh, Matrix4x4.identity, renderMaterial, 0); } renderUtil.Render(); Handles.SetCamera(renderUtil.camera); VectorShape.handleDrawSize = HandleUtility.GetHandleSize(Vector3.zero) * viewRect.height / viewRect.width; foreach (VectorShape selected in selection) { selected.DrawEditorHandles(true, (selected == focusedShape)); } if (selectionRect != Rect.zero) { Color outlineColor = Handles.color; Color fillColor = new Color(outlineColor.r, outlineColor.g, outlineColor.b, 0.2f); Handles.DrawSolidRectangleWithOutline(selectionRect, fillColor, outlineColor); } renderUtil.EndAndDrawPreview(viewRect); Vector2 originLoc = mouseToShapeMatrix.Inverse().MultiplyPoint(Vector2.zero); if (viewRect.Contains(originLoc)) { GUIStyle originPivot = "U2D.pivotDot"; if (originPivot != null) { Rect pivotRect = new Rect(0f, 0f, originPivot.fixedWidth, originPivot.fixedHeight); pivotRect.center = originLoc; originPivot.Draw(pivotRect, false, false, false, false); } } if (showSnap) { Vector2 snapLoc = mouseToShapeMatrix.Inverse().MultiplyPoint(snapPosition); if (viewRect.Contains(snapLoc)) { GUIStyle snapPivot = "U2D.dragDot"; if (snapPivot != null) { Rect pivotRect = new Rect(0f, 0f, snapPivot.fixedWidth, snapPivot.fixedHeight); pivotRect.center = snapLoc; snapPivot.Draw(pivotRect, false, false, false, false); } } } } else if (guiEvent.isScrollWheel && (EditorWindow.mouseOverWindow == this)) { float zoomFactor = HandleUtility.niceMouseDeltaZoom; float orthographicSize = renderUtil.camera.orthographicSize * (1 - zoomFactor * .02f); SetCameraSize(orthographicSize); handled = true; } else if (guiEvent.isMouse) { // Update mouse position mousePosition = guiEvent.mousePosition; mouseInContent = (viewRect.Contains(mousePosition)); switch (action) { case ActionType.ViewPan: case ActionType.ViewZoom: handled = OnViewToolMouse(guiEvent); break; case ActionType.SelectNormal: case ActionType.SelectAdditive: case ActionType.SelectSubtractive: handled = OnSelectToolMouse(guiEvent); break; case ActionType.LineEdit: case ActionType.CurveEdit: handled = OnBrushToolMouse(guiEvent); break; case ActionType.ShapeEdit: handled = OnShapeToolMouse(guiEvent); break; case ActionType.SetOrigin: handled = OnSetOriginMouse(guiEvent); break; //case ActionType.ChangeScale: //handled = OnChangeScaleMouse(guiEvent); //break; } if (!handled) { Vector2 delta = guiEvent.delta; guiEvent.mousePosition = MouseToShapePoint(mousePosition); guiEvent.delta = guiEvent.delta * new Vector2(mouseToShapeScale, -mouseToShapeScale); foreach (VectorShape selected in selection) { handled |= selected.HandleEditorEvent(guiEvent, true); } guiEvent.mousePosition = mousePosition; guiEvent.delta = delta; } } else if (guiEvent.type == EventType.ValidateCommand) { switch (guiEvent.commandName) { case Cmd_Delete: if (selection.Count > 0) { handled = true; } break; case Cmd_SelectAll: if (shapes.Count > 0) { handled = true; } break; } } else if (guiEvent.type == EventType.ExecuteCommand) { switch (guiEvent.commandName) { case Cmd_Delete: foreach (VectorShape selected in selection) { shapes.Remove(selected); } selection.Clear(); handled = true; break; case Cmd_SelectAll: foreach (VectorShape selected in shapes) { selection.Add(selected); } handled = true; break; case Cmd_ModifierKeysChanged: Repaint(); handled = true; break; } } if (action == ActionType.ChangeScale) { handled = OnChangeScaleGUI(guiEvent); } if (handled) { guiEvent.Use(); } }
void DrawPreview(bool save = false) { float iconPreviewBrightness = mIconPreviewBrightness.floatValue; Vector3 iconPreviewOffset = mIconPreviewOffset.vector3Value; Vector3 iconPreviewAngles = mIconPreviewAngles.vector3Value; Vector3 iconPreviewPosition = mIconPreviewPosition.vector3Value; Vector3 iconPreviewRotation = mIconPreviewRotation.vector3Value; Vector3 iconPreviewScale = mIconPreviewScale.vector3Value; if (mShouldRefresh || mCurrentPreviewBrightness != iconPreviewBrightness || mCurrentPreviewOffset != iconPreviewOffset || mCurrentPreviewAngles != iconPreviewAngles || mCurrentPreviewPosition != iconPreviewPosition || mCurrentPreviewRotation != iconPreviewRotation || mCurrentPreviewScale != iconPreviewScale || save || ShouldRefreshPreviewObject()) { DestroyPreview(); mShouldRefresh = false; mCurrentPreviewBrightness = iconPreviewBrightness; mCurrentPreviewOffset = iconPreviewOffset; mCurrentPreviewAngles = iconPreviewAngles; mCurrentPreviewPosition = iconPreviewPosition; mCurrentPreviewRotation = iconPreviewRotation; mCurrentPreviewScale = iconPreviewScale; mPreviewGameObject = CreatePreviewObject(); if (mPreviewGameObject != null) { mPreviewGameObject.hideFlags = HideFlags.HideAndDontSave; } } if (mPreviewGameObject == null && !save) { return; } if (mPreviewRenderUtility == null) { mPreviewRenderUtility = new PreviewRenderUtility(); mPreviewRenderUtility.camera.fieldOfView = 30.0f; mPreviewRenderUtility.camera.allowHDR = false; mPreviewRenderUtility.camera.allowMSAA = false; mPreviewRenderUtility.ambientColor = new Color(1.0f, 1.0f, 1.0f, 0.0f); mPreviewRenderUtility.lights[0].intensity = iconPreviewBrightness; mPreviewRenderUtility.lights[0].transform.position = iconPreviewOffset; mPreviewRenderUtility.lights[0].transform.eulerAngles = iconPreviewAngles; mPreviewRenderUtility.lights[1].intensity = iconPreviewBrightness; mPreviewRenderUtility.camera.transform.position = iconPreviewOffset; mPreviewRenderUtility.camera.transform.eulerAngles = iconPreviewAngles; mPreviewRenderUtility.camera.nearClipPlane = 0.1f; mPreviewRenderUtility.camera.farClipPlane = 10.0f; mPreviewRenderUtility.AddSingleGO(mPreviewGameObject); } mPreviewGameObject.transform.position = iconPreviewPosition; mPreviewGameObject.transform.eulerAngles = iconPreviewRotation; mPreviewGameObject.transform.localScale = iconPreviewScale; Rect previewRect = EditorGUILayout.GetControlRect(false, 200.0f); int previewID = GUIUtility.GetControlID(PreviewControlID, FocusType.Passive, previewRect); Event e = Event.current; EventType eventType = e.GetTypeForControl(previewID); bool repaint = eventType == EventType.Repaint; if (repaint || save) { Texture texture = null; mPreviewRenderUtility.BeginPreview(new Rect(0, 0, IconSize, IconSize), mGUIStyle); try { mPreviewRenderUtility.Render(false); } finally { texture = mPreviewRenderUtility.EndPreview(); } if (save) { UnityEngine.Object obj = serializedObject.targetObject; string path = $"Sprites/Inventory/{Category}/{obj.name}.png"; var rt = (RenderTexture)texture; int width = rt.width; int height = rt.height; RenderTexture.active = rt; try { var tex2D = new Texture2D(width, height, TextureFormat.RGB24, false); try { tex2D.ReadPixels(new Rect(0, 0, width, height), 0, 0); File.WriteAllBytes($"{Application.dataPath}/{path}", tex2D.EncodeToPNG()); } finally { DestroyImmediate(tex2D); } } finally { RenderTexture.active = null; } AssetDatabase.Refresh(); path = $"Assets/{path}"; TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter; importer.textureType = TextureImporterType.Sprite; importer.sRGBTexture = false; importer.alphaIsTransparency = true; importer.alphaSource = TextureImporterAlphaSource.None; importer.spritePixelsPerUnit = 100.0f; importer.mipmapEnabled = false; importer.maxTextureSize = IconSize; EditorUtility.SetDirty(importer); importer.SaveAndReimport(); mIcon.objectReferenceValue = AssetDatabase.LoadAssetAtPath(path, typeof(Sprite)); } if (repaint) { GUI.DrawTexture(previewRect, texture, ScaleMode.ScaleToFit, false); } } }