// UnityEditor.HandleUtility /// <summary> /// <para>Map a mouse drag onto a movement along a line in 3D space.</para> /// </summary> /// <param name="src">The source point of the drag.</param> /// <param name="dest">The destination point of the drag.</param> /// <param name="srcPosition">The 3D position the dragged object had at src ray.</param> /// <param name="constraintDir">3D direction of constrained movement.</param> /// <returns> /// <para>The distance travelled along constraintDir.</para> /// </returns> public static float CalcLineTranslation(Vector2 src, Vector2 dest, Vector3 srcPosition, Vector3 constraintDir, Matrix4x4 handleMatrix) { srcPosition = handleMatrix.MultiplyPoint(srcPosition); constraintDir = handleMatrix.MultiplyVector(constraintDir); float num = 1f; Vector3 forward = Camera.main.transform.forward; if(Vector3.Dot(constraintDir, forward) < 0f) { num = -1f; } Vector3 vector = constraintDir; vector.y = -vector.y; Camera current = Camera.main; Vector2 vector2 = PixelsToPoints(current.WorldToScreenPoint(srcPosition)); Vector2 vector3 = PixelsToPoints(current.WorldToScreenPoint(srcPosition + constraintDir * num)); Vector2 x = dest; Vector2 x2 = src; if(vector2 == vector3) { return 0f; } //x.y = -x.y; //x2.y = -x2.y; float parametrization = GetParametrization(x2, vector2, vector3); float parametrization2 = GetParametrization(x, vector2, vector3); return (parametrization2 - parametrization) * num; }
public void DrawGizmos(MegaFFD ffd, Matrix4x4 tm) { Handles.color = Color.red; int pc = ffd.GridSize(); for ( int i = 0; i < pc; i++ ) { for ( int j = 0; j < pc; j++ ) { for ( int k = 0; k < pc; k++ ) { pp3[0] = tm.MultiplyPoint(ffd.GetPoint(i, j, k) + ffd.bcenter); if ( i < pc - 1 ) { pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i + 1, j, k) + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } if ( j < pc - 1 ) { pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j + 1, k) + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } if ( k < pc - 1 ) { pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j, k + 1) + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } } } } }
public override void GetTransform(PropSocket socket, DungeonModel model, Matrix4x4 propTransform, System.Random random, out Vector3 outPosition, out Quaternion outRotation, out Vector3 outScale) { base.GetTransform(socket, model, propTransform, random, out outPosition, out outRotation, out outScale); var angle = random.Range(0, 1) * 180; var rotation = Quaternion.Euler(0, angle, 0); outRotation = rotation; }
/// <summary> /// Draws a gizmo cylinder with the given TRS matrix and color /// </summary> /// <param name="trs"></param> /// <param name="color"></param> public static void DrawCylinder(Matrix4x4 trs, Color color) { if (cylVerts == null || cylTris == null) { GameObject cyl = GameObject.CreatePrimitive( PrimitiveType.Cylinder); MeshFilter filter = cyl.GetComponent<MeshFilter>(); cylVerts = filter.sharedMesh.vertices; cylTris = filter.sharedMesh.triangles; GameObject.DestroyImmediate(cyl); } Vector3[] verts = new Vector3[cylVerts.Length]; for (int i = 0; i < cylVerts.Length; i++) verts[i] = trs.MultiplyPoint(cylVerts[i]); Gizmos.color = color; for (int i = 0; i < cylTris.Length / 3; i++) { int j = i * 3; Gizmos.DrawLine(verts[cylTris[j]], verts[cylTris[j + 1]]); Gizmos.DrawLine(verts[cylTris[j + 1]], verts[cylTris[j + 2]]); Gizmos.DrawLine(verts[cylTris[j + 2]], verts[cylTris[j]]); } }
/// <summary> /// Converts vector data stored within a texture using the specified basis. Assume all calculations are performed in tangent space. /// </summary> /// <param name='basis'> /// Basis to multiply the vector values against. /// </param> /// <param name='vectorData'> /// Texture2D containing vector data. Textures are passed by reference, so make sure to copy beforehand if you don't want to overwrite your data! /// </param> public static void ConvertTangentBasis(Matrix4x4 basis, ref Texture2D vectorData, bool recomputeZ = false) { Color[] colorData = vectorData.GetPixels(); Texture2D tmpTexture = new Texture2D(vectorData.width, vectorData.height, TextureFormat.ARGB32, false); for (int i = 0; i < colorData.Length; i++) { Color vecData = new Color(colorData[i].r, colorData[i].g, colorData[i].b, 1); vecData.r = Vector3.Dot(new Vector3(basis.m00, basis.m01, basis.m02), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f; vecData.g = Vector3.Dot(new Vector3(basis.m10, basis.m11, basis.m12), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f; if (recomputeZ) { vecData.r = vecData.r * 2 - 1; vecData.g = vecData.g * 2 - 1; vecData.b = Mathf.Sqrt(1 - vecData.r * vecData.r - vecData.g * vecData.g) * 0.5f + 0.5f; vecData.r = vecData.r * 0.5f + 0.5f; vecData.g = vecData.g * 0.5f + 0.5f; } else { vecData.b = Vector3.Dot(new Vector3(basis.m20, basis.m21, basis.m22), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f; } colorData[i] = vecData; } tmpTexture.SetPixels(colorData); tmpTexture.Apply(); vectorData = tmpTexture; }
// Use this for initialization void Awake() { GameObject go = new GameObject("depthCamera"); depthCamera = go.AddComponent<Camera>(); depthCamera.transform.position = Vector3.zero; depthCamera.transform.rotation = transform.rotation; depthCamera.transform.localPosition += transform.forward * Near; depthCamera.transform.parent = transform; depthCamera.isOrthoGraphic = true; depthCamera.clearFlags = CameraClearFlags.SolidColor; depthCamera.backgroundColor = Color.white; depthTexture = new RenderTexture(TextureSize,TextureSize, 16, RenderTextureFormat.ARGB32); depthTexture.filterMode = FilterMode.Point; depthCamera.targetTexture = depthTexture; depthCamera.SetReplacementShader(shader, null); depthCamera.enabled = false; biasMatrix = Matrix4x4.identity; biasMatrix[ 0, 0 ] = 0.5f; biasMatrix[ 1, 1 ] = 0.5f; biasMatrix[ 2, 2 ] = 0.5f; biasMatrix[ 0, 3 ] = 0.5f; biasMatrix[ 1, 3 ] = 0.5f; biasMatrix[ 2, 3 ] = 0.5f; }
void Start() { // This creates the diagonalised inertia tensor matrix from the Vector3 by the physics engine. // Note the physics engine is using the colliders of the object and it's children, and // the mass of the parent object to calculate an approximate inertia tensor. __inertiaTensor = Matrix4x4.Scale (GetComponent<Rigidbody>().inertiaTensor); }
//called when data for any output pin is requested public void Evaluate(int SpreadMax) { FView.SliceCount = FProjection.SliceCount = FViewProjection.SliceCount = SpreadMax; for (int i = 0; i < SpreadMax; i++) { var translate = FTranslate[i]; var rotate = FRotate[i]; var fov = FFov[i]; var shift = FShift[i]; var near = FNear[i]; var far = FFar[i]; var aspect = FAspect[i]; var view = VMath.Inverse( VMath.Rotate(rotate * Math.PI * 2) * VMath.Translate(translate) ); double scaleX = 1.0/Math.Tan(fov[0] * Math.PI); double scaleY = 1.0/Math.Tan(fov[1] * Math.PI); double fn = far / (far - near); var proj = new Matrix4x4(scaleX, 0, 0, 0, 0, scaleY, 0, 0, -2*shift.x, -2*shift.y, fn, 1, 0, 0, -near*fn, 0); FView[i] = view; FProjection[i] = proj; FViewProjection[i] = view * proj; } }
// From http://docs.unity3d.com/ScriptReference/Camera-projectionMatrix.html static Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far) { float x = 2.0F * near / (right - left); float y = 2.0F * near / (top - bottom); float a = (right + left) / (right - left); float b = (top + bottom) / (top - bottom); float c = -(far + near) / (far - near); float d = -(2.0F * far * near) / (far - near); float e = -1.0F; Matrix4x4 m = new Matrix4x4(); m[0, 0] = x; m[0, 1] = 0; m[0, 2] = a; m[0, 3] = 0; m[1, 0] = 0; m[1, 1] = y; m[1, 2] = b; m[1, 3] = 0; m[2, 0] = 0; m[2, 1] = 0; m[2, 2] = c; m[2, 3] = d; m[3, 0] = 0; m[3, 1] = 0; m[3, 2] = e; m[3, 3] = 0; return m; }
public void Start() { fxRes = GetComponent<IndieEffects>(); blurMat = new Material(shader); previousViewProjectionMatrix = fxRes.DepthCam.camera.projectionMatrix * fxRes.DepthCam.camera.worldToCameraMatrix; }
// Use this for initialization void Start () { kinect = devOrEmu.getKinect(); players = new Kinect.NuiSkeletonTrackingState[Kinect.Constants.NuiSkeletonCount]; trackedPlayers = new int[Kinect.Constants.NuiSkeletonMaxTracked]; trackedPlayers[0] = -1; trackedPlayers[1] = -1; bonePos = new Vector3[2,(int)Kinect.NuiSkeletonPositionIndex.Count]; rawBonePos = new Vector3[2,(int)Kinect.NuiSkeletonPositionIndex.Count]; boneVel = new Vector3[2,(int)Kinect.NuiSkeletonPositionIndex.Count]; boneState = new Kinect.NuiSkeletonPositionTrackingState[2,(int)Kinect.NuiSkeletonPositionIndex.Count]; boneLocalOrientation = new Quaternion[2, (int)Kinect.NuiSkeletonPositionIndex.Count]; boneAbsoluteOrientation = new Quaternion[2, (int)Kinect.NuiSkeletonPositionIndex.Count]; //create the transform matrix that converts from kinect-space to world-space Matrix4x4 trans = new Matrix4x4(); trans.SetTRS( new Vector3(-kinect.getKinectCenter().x, kinect.getSensorHeight()-kinect.getKinectCenter().y, -kinect.getKinectCenter().z), Quaternion.identity, Vector3.one ); Matrix4x4 rot = new Matrix4x4(); Quaternion quat = new Quaternion(); double theta = Mathf.Atan((kinect.getLookAt().y+kinect.getKinectCenter().y-kinect.getSensorHeight()) / (kinect.getLookAt().z + kinect.getKinectCenter().z)); float kinectAngle = (float)(theta * (180 / Mathf.PI)); quat.eulerAngles = new Vector3(-kinectAngle, 0, 0); rot.SetTRS( Vector3.zero, quat, Vector3.one); //final transform matrix offsets the rotation of the kinect, then translates to a new center kinectToWorld = flipMatrix*trans*rot; }
public void createCylinder(float radius, float height, int slices, GameObject go, Matrix4x4 matrix) { Mesh cylinderMesh = new Mesh(); vertices = new Vector3[(slices+1) * 4]; Vector3[] cylPoints1 = createCylinderPoints(radius, height, slices, true); Vector3[] cylPoints2 = createCylinderPoints(radius, height, slices, false); for (int i = 0; i <cylPoints1.Length; i++) { vertices[i] = cylPoints1[i]; } for (int k = 0; k < cylPoints2.Length; k++) { vertices[k + cylPoints1.Length] = cylPoints2[k]; } createCylinderNormals(vertices, radius); for (int j = 0; j < vertices.Length; j++) { vertices[j] = matrix.MultiplyPoint(vertices[j]); normals[j] = matrix.MultiplyPoint(normals[j]); } trianglesIndex = 0; createCylinderTriangles(slices+1); cylinderMesh.vertices = vertices; cylinderMesh.triangles = triangles; cylinderMesh.normals = normals; cylinderMesh.uv = uvs; MeshFilter filter = (MeshFilter)go.GetComponent("MeshFilter"); filter.mesh = cylinderMesh; }
public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material) { MaterialPropertyBlock properties = null; int shaderPass = -1; int submeshIndex = 0; CommandBuffer.INTERNAL_CALL_DrawMesh(this, mesh, ref matrix, material, submeshIndex, shaderPass, properties); }
//Scale point along stretchAxis by stretchFactor public static Vector3 StretchAlongAxis( Vector3 point, Vector3 stretchAxis, float stretchFactor ) { var upVector = Vector3.up; //Check if vectors are colliniar if( Vector3.Dot(upVector, stretchAxis) >= 1.0f - epsilon ) upVector = Vector3.left; var right = Vector3.Cross(upVector, stretchAxis); var up = Vector3.Cross(stretchAxis, right); var forward = stretchAxis; right.Normalize(); up.Normalize(); forward.Normalize(); Matrix4x4 rotate = new Matrix4x4(); rotate.SetColumn(0, right); rotate.SetColumn(1, up); rotate.SetColumn(2, forward); rotate[3, 3] = 1.0F; Matrix4x4 scale = new Matrix4x4(); scale[0, 0] = 1.0f; scale[1, 1] = 1.0f; scale[2, 2] = stretchFactor; scale[3, 3] = 1.0f; Matrix4x4 trans = rotate * scale * rotate.transpose; return trans.MultiplyPoint3x4( point ); }
public Matrix4x4 GetMatrix(){ Matrix4x4 keystone = new Matrix4x4(); // a b c d // e f g h // i j 1 0 // m n 0 1 keystone[0, 0] = a; keystone[0, 1] = b; //keystone[0, 2] = c; keystone[0, 3] = d; keystone[1, 0] = e; keystone[1, 1] = f; //keystone[1, 2] = g; keystone[1, 3] = h; keystone[2, 0] = 0; keystone[2, 1] = 0; keystone[2, 2] = 1 - Mathf.Abs(m) - Mathf.Abs(n); keystone[2, 3] = 0; keystone[3, 0] = m; keystone[3, 1] = n; keystone[3, 2] = 0; keystone[3, 3] = 1; return keystone; }
Matrix4x4 buildProjectionMatrix (float[] cameraParam, float w, float h) { float near = 0.01f; // Near clipping distance float far = 100f; // Far clipping distance Matrix4x4 projectionMatrix = new Matrix4x4 (); // Camera parameters float f_x = cameraParam [0]; // Focal length in x axis float f_y = cameraParam [1]; // Focal length in y axis (usually the same?) float c_x = cameraParam [2]; // Camera primary point x float c_y = cameraParam [3]; // Camera primary point y projectionMatrix [0] = 2.0f * f_x / w; projectionMatrix [1] = 0.0f; projectionMatrix [2] = 0.0f; projectionMatrix [3] = 0.0f; projectionMatrix [4] = 0.0f; projectionMatrix [5] = 2.0f * f_y / h; projectionMatrix [6] = 0.0f; projectionMatrix [7] = 0.0f; projectionMatrix [8] = 2.0f * c_x / w - 1.0f; projectionMatrix [9] = 2.0f * c_y / h - 1.0f; projectionMatrix [10] = -(far + near) / (far - near); projectionMatrix [11] = -1.0f; projectionMatrix [12] = 0.0f; projectionMatrix [13] = 0.0f; projectionMatrix [14] = -2.0f * far * near / (far - near); projectionMatrix [15] = 0.0f; return projectionMatrix; }
// Update is called once per frame void Update() { if(Input.GetButtonDown("Fire1")) { Shot(); } if(Input.GetButtonDown("Fire2")) { Blow(); } { Vector3 move = Vector3.zero; move.x = Input.GetAxis ("Horizontal"); move.z = Input.GetAxis ("Vertical"); trans.position += move * 0.1f; } { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Plane plane = new Plane(Vector3.up, Vector3.zero); float distance = 0; if (plane.Raycast(ray, out distance)){ trans.rotation = Quaternion.LookRotation(ray.GetPoint(distance) - trans.position); } } { Matrix4x4 ts = Matrix4x4.identity; ts.SetColumn (3, new Vector4(0.0f,0.0f,0.5f,1.0f)); ts = Matrix4x4.Scale(new Vector3(5.0f, 5.0f, 10.0f)) * ts; blowMatrix = trans.localToWorldMatrix * ts; } }
void Proj() { world2MirCam = mirCam.transform.worldToLocalMatrix;// projM = mirCam.projectionMatrix; projM.m32 = 1f; cm = correction * projM * world2MirCam; }
public void UpdateCameraMatrix( ) { SelectMode(); /* float left = 0.0f; float top = 0.0f; float right = cam.pixelWidth, bottom = cam.pixelHeight; float far = cam.farClipPlane; float near = cam.near; float x = (2.0f) / (right - left) * scale; float y = (2.0f) / (bottom - top) * scale; float z = -2.0f / (far - near); float a = 0; float b = 0; float c = -(2.0f * far * near) / (far - near); */ Matrix4x4 m = new Matrix4x4(); float x = 0.67f; float y = 1.0f; float z = -0.02f; float a = 0; float b = 0; float c = -0.2f; m[0,0] = x; m[0,1] = 0; m[0,2] = 0; m[0,3] = a; m[1,0] = 0; m[1,1] = y; m[1,2] = 0; m[1,3] = b; m[2,0] = 0; m[2,1] = 0; m[2,2] = z; m[2,3] = c; m[3,0] = 0; m[3,1] = 0; m[3,2] = 0; m[3,3] = 1; //Debug.Log(": x "+x+": y "+y+": z "+z); //Debug.Log(": a "+a+": b "+b+": c "+c); cam.projectionMatrix = m; }
private static Matrix4x4 PerspectiveOffCenter( NearPlane plane ) { float x = ( 2.0f*plane.near )/( plane.right - plane.left ); float y = ( 2.0f*plane.near )/( plane.top - plane.bottom ); float a = ( plane.right + plane.left )/( plane.right - plane.left ); float b = ( plane.top + plane.bottom )/( plane.top - plane.bottom ); float c = -( plane.far + plane.near )/( plane.far - plane.near ); float d = -( 2.0f*plane.far*plane.near )/( plane.far - plane.near ); float e = -1.0f; Matrix4x4 m = new Matrix4x4 (); m[0, 0] = x; m[0, 1] = 0.0f; m[0, 2] = a; m[0, 3] = 0.0f; m[1, 0] = 0.0f; m[1, 1] = y; m[1, 2] = b; m[1, 3] = 0.0f; m[2, 0] = 0.0f; m[2, 1] = 0.0f; m[2, 2] = c; m[2, 3] = d; m[3, 0] = 0.0f; m[3, 1] = 0.0f; m[3, 2] = e; m[3, 3] = 0.0f; return m; }
/// <summary> /// Calculate bone transforms from world transforms /// </summary> /// <param name="hierarchy">Hierarchy of the skeleton, value for a given index indicates the parent index of the bone at the given index</param> /// <param name="worldTransforms">The world transforms to turn into bone transforms</param> /// <param name="calculatedBoneTransforms">An array to write the bone transforms into</param> public static void CalculateBoneTransformsFromWorldTransforms(IList<int> hierarchy, IReadOnlyList<Matrix4x4> worldTransforms, Matrix4x4[] calculatedBoneTransforms) { if (calculatedBoneTransforms == null) throw new ArgumentNullException("calculatedBoneTransforms"); if (worldTransforms == null) throw new ArgumentNullException("worldTransforms"); unsafe { //Allocate a place to temporarily store the inverted transforms Matrix4x4* inverseWorldTransforms = stackalloc Matrix4x4[worldTransforms.Count]; //Calculate inverse world transforms for each bone for (var i = 0; i < calculatedBoneTransforms.Length; i++) Matrix4x4.Invert(worldTransforms[i], out inverseWorldTransforms[i]); //Calculate bone transforms for each bone for (var bone = 0; bone < worldTransforms.Count; bone++) { var parentBone = hierarchy[bone]; if (parentBone == -1) calculatedBoneTransforms[bone] = worldTransforms[bone]; else calculatedBoneTransforms[bone] = Matrix4x4.Multiply(worldTransforms[bone], inverseWorldTransforms[parentBone]); } } }
public static void DrawWireCube(Matrix4x4 mat, Color col) { const float s = 0.5f; Vector4[] vertices = new Vector4[8] { new Vector4( s, s, s, 1.0f), new Vector4(-s, s, s, 1.0f), new Vector4( s,-s, s, 1.0f), new Vector4( s, s,-s, 1.0f), new Vector4(-s,-s, s, 1.0f), new Vector4( s,-s,-s, 1.0f), new Vector4(-s, s,-s, 1.0f), new Vector4(-s,-s,-s, 1.0f), }; for (int i = 0; i < vertices.Length; ++i ) { vertices[i] = mat * vertices[i]; } int[] indices = new int[24] { 0,1, 0,2, 0,3, 1,4, 1,6, 2,4, 2,5, 3,5, 3,6, 4,7, 5,7, 6,7 }; GL.Begin(GL.LINES); GL.Color(col); for (int i = 0; i < indices.Length; ++i ) { GL.Vertex(vertices[indices[i]]); } GL.End(); }
public void Matrix4x4DeterminantTest1() { Matrix4x4 a = new Matrix4x4(); a.M11 = 5.0f; a.M12 = 2.0f; a.M13 = 8.25f; a.M14 = 1.0f; a.M21 = 12.0f; a.M22 = 6.8f; a.M23 = 2.14f; a.M24 = 9.6f; a.M31 = 6.5f; a.M32 = 1.0f; a.M33 = 3.14f; a.M34 = 2.22f; a.M41 = 0f; a.M42 = 0.86f; a.M43 = 4.0f; a.M44 = 1.0f; Matrix4x4 i; Assert.True(Matrix4x4.Invert(a, out i)); float detA = a.GetDeterminant(); float detI = i.GetDeterminant(); float t = 1.0f / detI; // only accurate to 3 precision Assert.True(System.Math.Abs(detA - t) < 1e-3, "Matrix4x4.Determinant was not set correctly."); }
public void BeginUIResizing() { Vector2 nativeSize = NativeResolution; _didResizeUI = true; stack.Add (GUI.matrix); Matrix4x4 m = new Matrix4x4 (); float w = Screen.width; float h = Screen.height; float aspect = w / h; if (aspect < (nativeSize.x / nativeSize.y)) { //screen is taller _guiScaleFactor = (Screen.width / nativeSize.x); _offset.y = (Screen.height - (nativeSize.y * _guiScaleFactor)) * 0.5f; } else { //screen is wider _guiScaleFactor = (Screen.height/nativeSize.y); _offset.x = (Screen.width-(nativeSize.x*_guiScaleFactor))*0.5f; } m.SetTRS (_offset,Quaternion.identity,Vector3.one*_guiScaleFactor); GUI.matrix *= m; }
public void Matrix4x4IdentityTest() { Matrix4x4 val = new Matrix4x4(); val.M11 = val.M22 = val.M33 = val.M44 = 1.0f; Assert.True(MathHelper.Equal(val, Matrix4x4.Identity), "Matrix4x4.Indentity was not set correctly."); }
void CalculateTargetValues(ref float[] param) { float len=vecLength3(targetMatrix[12],targetMatrix[13],targetMatrix[14]-0.17f); param[2]=len-L1; if(len!=0){ float tmp=targetMatrix[12]/len; tmp=tmp>+1?+1:tmp; tmp=tmp<-1?-1:tmp; param[1]=Mathf.Asin(tmp); tmp=-targetMatrix[13]/(len*Mathf.Cos(param[1])); tmp=tmp>+1?+1:tmp; tmp=tmp<-1?-1:tmp; param[0]=Mathf.Asin(tmp); }else{ param[0]=0; param[1]=0; } Matrix4x4 mat,tmpM,tmpM2; mat=new Matrix4x4(); MakeMatrix(myAxis.axisX,0,0,0,-0.17f,ref mat); tmpM2=mat*targetMatrix; MakeMatrix(myAxis.axisX,-param[0],0,0,0,ref mat); tmpM=mat*tmpM2; MakeMatrix(myAxis.axisY,-param[1],0,0,-len,ref mat); tmpM2=mat*tmpM; MatrixtoXYZ(tmpM2,ref param[3],ref param[4],ref param[5]); param[3]=-param[3]; param[4]=-param[4]; param[5]=-param[5]; }
void ConvertToMatrix(Quaternion q, Vector3 pos, ref Matrix4x4 mat) { Matrix4x4 m=new Matrix4x4(); qtomatrix(ref m, q); //added by yamen: include head position in the matrix m[3,0] = pos[0]; m[3,1] = pos[1]; m[3,2] = pos[2]; mat[0] = m[0,0]; mat[1] = m[1,0]; mat[2] = m[2,0]; mat[3] = 0; mat[4] = m[0,1]; mat[5] = m[1,1]; mat[6] = m[2,1]; mat[7] = 0; mat[8] = m[0,2]; mat[9] = m[1,2]; mat[10] = m[2,2]; mat[11] = 0; mat[12] = m[3,0]; mat[13] = m[3,1]; mat[14] = m[3,2]; mat[15] = 1; }
void LateUpdate() { RightHandMatrix = ChangeCoordinateSystems(HandR, Gun); LeftHandMatrix = ChangeCoordinateSystems(HandL, Gun); Gun.LookAt(AimPoint.transform.position); Gun.transform.Rotate(Vector3.up, 90); //Right arm Vector3 desiredRightWristPosition = (Gun.localToWorldMatrix * RightHandMatrix).MultiplyPoint3x4 (Vector3.zero); Transform[] bonesR = new Transform[3]; bonesR[0]=ArmR; bonesR[1]=ForearmR; bonesR[2]=HandR; IKSolver.Solve( bonesR, desiredRightWristPosition ); HandR.rotation = QuatFromMatrix(Gun.localToWorldMatrix * RightHandMatrix); //Left arm Vector3 desiredLeftWristPosition = (Gun.localToWorldMatrix * LeftHandMatrix).MultiplyPoint3x4 (Vector3.zero); Transform[] bonesL = new Transform[3]; bonesL[0] = ArmL; bonesL[1] =ForearmL; bonesL[2] = HandL; IKSolver.Solve( bonesL, desiredLeftWristPosition ); HandL.rotation = QuatFromMatrix(Gun.localToWorldMatrix * RightHandMatrix); }
/// <inheritdoc/> protected override void OnApply(ImageBase source, ImageBase target, Rectangle targetRectangle, Rectangle sourceRectangle) { float saturationFactor = this.saturation / 100f; // Stop at -1 to prevent inversion. saturationFactor++; // The matrix is set up to "shear" the colour space using the following set of values. // Note that each colour component has an effective luminance which contributes to the // overall brightness of the pixel. // See http://graficaobscura.com/matrix/index.html float saturationComplement = 1.0f - saturationFactor; float saturationComplementR = 0.3086f * saturationComplement; float saturationComplementG = 0.6094f * saturationComplement; float saturationComplementB = 0.0820f * saturationComplement; Matrix4x4 matrix4X4 = new Matrix4x4() { M11 = saturationComplementR + saturationFactor, M12 = saturationComplementR, M13 = saturationComplementR, M21 = saturationComplementG, M22 = saturationComplementG + saturationFactor, M23 = saturationComplementG, M31 = saturationComplementB, M32 = saturationComplementB, M33 = saturationComplementB + saturationFactor, }; this.matrix = matrix4X4; }
public void SetPose(Matrix4x4 pose, CoordinateSpace space = CoordinateSpace.Local) { if (space == CoordinateSpace.Global) _rigidBody.WrappedRigidBody.PoseCenterOfMass = pose.ToDigitalRune(); else _rigidBody.WrappedRigidBody.MassFrame.Pose = pose.ToDigitalRune(); }
public static Matrix4x4 GetMatrix(this Rigidbody body) { return(Matrix4x4.TRS( body.position, body.rotation, body.transform.lossyScale)); }
// only update stiffness and keep bone length void SkipUpdateParticles() { for (int i = 0; i < m_Particles.Count; ++i) { Particle p = m_Particles[i]; if (p.m_ParentIndex >= 0) { p.m_PrevPosition += m_ObjectMove; p.m_Position += m_ObjectMove; Particle p0 = m_Particles[p.m_ParentIndex]; float restLen; if (p.m_Transform != null) { restLen = (p0.m_Transform.position - p.m_Transform.position).magnitude; } else { restLen = p0.m_Transform.localToWorldMatrix.MultiplyVector(p.m_EndOffset).magnitude; } // keep shape float stiffness = Mathf.Lerp(1.0f, p.m_Stiffness, m_Weight); if (stiffness > 0) { Matrix4x4 m0 = p0.m_Transform.localToWorldMatrix; m0.SetColumn(3, p0.m_Position); Vector3 restPos; if (p.m_Transform != null) { restPos = m0.MultiplyPoint3x4(p.m_Transform.localPosition); } else { restPos = m0.MultiplyPoint3x4(p.m_EndOffset); } Vector3 d = restPos - p.m_Position; float len = d.magnitude; float maxlen = restLen * (1 - stiffness) * 2; if (len > maxlen) { p.m_Position += d * ((len - maxlen) / len); } } // keep length Vector3 dd = p0.m_Position - p.m_Position; float leng = dd.magnitude; if (leng > 0) { p.m_Position += dd * ((leng - restLen) / leng); } } else { p.m_PrevPosition = p.m_Position; p.m_Position = p.m_Transform.position; } } }
void UpdateParticles2() { Plane movePlane = new Plane(); for (int i = 1; i < m_Particles.Count; ++i) { Particle p = m_Particles[i]; Particle p0 = m_Particles[p.m_ParentIndex]; float restLen; if (p.m_Transform != null) { restLen = (p0.m_Transform.position - p.m_Transform.position).magnitude; } else { restLen = p0.m_Transform.localToWorldMatrix.MultiplyVector(p.m_EndOffset).magnitude; } // keep shape float stiffness = Mathf.Lerp(1.0f, p.m_Stiffness, m_Weight); if (stiffness > 0 || p.m_Elasticity > 0) { Matrix4x4 m0 = p0.m_Transform.localToWorldMatrix; m0.SetColumn(3, p0.m_Position); Vector3 restPos; if (p.m_Transform != null) { restPos = m0.MultiplyPoint3x4(p.m_Transform.localPosition); } else { restPos = m0.MultiplyPoint3x4(p.m_EndOffset); } Vector3 d = restPos - p.m_Position; p.m_Position += d * p.m_Elasticity; if (stiffness > 0) { d = restPos - p.m_Position; float len = d.magnitude; float maxlen = restLen * (1 - stiffness) * 2; if (len > maxlen) { p.m_Position += d * ((len - maxlen) / len); } } } // collide if (m_Colliders != null) { float particleRadius = p.m_Radius * m_ObjectScale; for (int j = 0; j < m_Colliders.Count; ++j) { DynamicBoneCollider c = m_Colliders[j]; if (c != null && c.enabled) { c.Collide(ref p.m_Position, particleRadius); } } } // freeze axis, project to plane if (m_FreezeAxis != FreezeAxis.None) { switch (m_FreezeAxis) { case FreezeAxis.X: movePlane.SetNormalAndPosition(p0.m_Transform.right, p0.m_Position); break; case FreezeAxis.Y: movePlane.SetNormalAndPosition(p0.m_Transform.up, p0.m_Position); break; case FreezeAxis.Z: movePlane.SetNormalAndPosition(p0.m_Transform.forward, p0.m_Position); break; } p.m_Position -= movePlane.normal * movePlane.GetDistanceToPoint(p.m_Position); } // keep length Vector3 dd = p0.m_Position - p.m_Position; float leng = dd.magnitude; if (leng > 0) { p.m_Position += dd * ((leng - restLen) / leng); } } }
private static Matrix ConvertSystemNumericsToSharpDX(Matrix4x4 value) => new Matrix( value.M11, value.M12, value.M13, value.M14, value.M21, value.M22, value.M23, value.M24, value.M31, value.M32, value.M33, value.M34, value.M41, value.M42, value.M43, value.M44);
private static void Render(Scene scene, IRenderContext renderer) { scene.SetCamera(cameraTarget + cameraOffset, ComputeProjViewMatrix(graphicsLoop.Form.ClientSize)); scene.AddRenderable( graphicsLoop.Presets.UnitCube, Matrix.Identity, SomewhatRough, SDXColor.White); var terrainOverlayNetwork = game.TerrainService.CompileSnapshot().OverlayNetworkManager.CompileTerrainOverlayNetwork(0); foreach (var node in terrainOverlayNetwork.TerrainNodes) { if (!lgvMeshesByLgvGuid.TryGetValue(node.LocalGeometryView.Guid, out var mesh)) { VertexPositionNormalColorTexture[] F(Triangle3 triangle) => triangle.Points.Map( p => new VertexPositionNormalColorTexture( new SDXVector3((float)p.X, (float)p.Y, 0), -SDXVector3.UnitZ, SDXColor.White, new SDXVector2(0, 0))); var triangleList = node.LocalGeometryView.Triangulation.Islands .SelectMany(i => i.Triangles) .SelectMany(triangle => F(triangle).Concat(F(triangle).Reverse())) .ToArray(); mesh = graphicsLoop.GraphicsFacade.CreateMesh(triangleList); lgvMeshesByLgvGuid.Add(node.LocalGeometryView.Guid, mesh); } scene.AddRenderable( mesh, ConvertSystemNumericsToSharpDX(Matrix4x4.Transpose(node.SectorNodeDescription.WorldTransform)), SomewhatRough, SDXColor.White); } if (terrainOverlayNetwork.TryFindTerrainOverlayNode(baddie.MovementComponent.WorldPosition, out var n)) { debugCanvas.DrawCrossSectorVisibilityPolygon(n, baddie.MovementComponent.LocalPositionIv2); } else { Console.WriteLine("Err, can't find pos?"); } debugCanvas.Transform = Matrix4x4.Identity; debugCanvas.DrawLineStrip(fred, StrokeStyle.RedThick5Solid); scene.AddRenderable( graphicsLoop.Presets.UnitSphere, MatrixCM.Translation(player.MovementComponent.WorldPosition.ToSharpDX()) * MatrixCM.Scaling(player.MovementComponent.BaseRadius * 2), SomewhatRough, SDXColor.Lime); scene.AddRenderable( graphicsLoop.Presets.UnitSphere, MatrixCM.Translation(baddie.MovementComponent.WorldPosition.ToSharpDX()) * MatrixCM.Scaling(baddie.MovementComponent.BaseRadius * 2), SomewhatRough, SDXColor.Red); foreach (var rock in rocks) { scene.AddRenderable( graphicsLoop.Presets.UnitSphere, MatrixCM.Translation(rock.MovementComponent.WorldPosition.ToSharpDX()) * MatrixCM.Scaling(rock.MovementComponent.BaseRadius * 2), SomewhatRough, SDXColor.Brown); } debugCanvas.DrawEntityPaths(game.EntityService); var snapshot = scene.ExportSnapshot(); renderer.RenderScene(snapshot); snapshot.ReleaseReference(); }
public GizmosMatrixScope(Matrix4x4 c) { recordMatrix = Gizmos.matrix; Gizmos.matrix = c; }
public static Pose GetPose(this Matrix4x4 matrix) { return(new Pose(matrix.MultiplyPoint3x4(Vector3.zero), matrix.rotation)); }
/// <summary> /// Convenience function that figures out the panel's correct change flag by searching the parents. /// </summary> int GetChangeFlag (UINode start) { int flag = start.changeFlag; if (flag == -1) { Transform trans = start.trans.parent; UINode sub; // Keep going until we find a set flag for (;;) { // Check the parent's flag #if UNITY_FLASH if (mChildren.TryGetValue(trans, out sub)) { #else if (mChildren.Contains(trans)) { sub = (UINode)mChildren[trans]; #endif flag = sub.changeFlag; trans = trans.parent; // If the flag hasn't been set either, add this child to the hierarchy if (flag == -1) mHierarchy.Add(sub); else break; } else { flag = 0; break; } } // Update the parent flags for (int i = 0, imax = mHierarchy.Count; i < imax; ++i) { UINode pc = mHierarchy[i]; pc.changeFlag = flag; } mHierarchy.Clear(); } return flag; } /// <summary> /// Update the world-to-local transform matrix as well as clipping bounds. /// </summary> void UpdateTransformMatrix () { float time = Time.realtimeSinceStartup; if (time == 0f || mMatrixTime != time) { mMatrixTime = time; mWorldToLocal = cachedTransform.worldToLocalMatrix; if (mClipping != UIDrawCall.Clipping.None) { Vector2 size = new Vector2(mClipRange.z, mClipRange.w); if (size.x == 0f) size.x = (mCam == null) ? Screen.width : mCam.pixelWidth; if (size.y == 0f) size.y = (mCam == null) ? Screen.height : mCam.pixelHeight; size *= 0.5f; mMin.x = mClipRange.x - size.x; mMin.y = mClipRange.y - size.y; mMax.x = mClipRange.x + size.x; mMax.y = mClipRange.y + size.y; } } } /// <summary> /// Run through all managed transforms and see if they've changed. /// </summary> void UpdateTransforms () { bool transformsChanged = mCheckVisibility; // Check to see if something has changed #if UNITY_FLASH foreach (KeyValuePair<Transform, UINode> child in mChildren) { UINode node = child.Value; #else for (int i = 0, imax = mChildren.Count; i < imax; ++i) { UINode node = (UINode)mChildren[i]; #endif if (node.trans == null) { mRemoved.Add(node.trans); continue; } if (node.HasChanged()) { node.changeFlag = 1; transformsChanged = true; } else node.changeFlag = -1; } // Clean up the deleted transforms for (int i = 0, imax = mRemoved.Count; i < imax; ++i) mChildren.Remove(mRemoved[i]); mRemoved.Clear(); // If something has changed, propagate the changes *down* the tree hierarchy (to children). // An alternative (but slower) approach would be to do a pc.trans.GetComponentsInChildren<UIWidget>() // in the loop above, and mark each one as dirty. if (transformsChanged || mRebuildAll) { #if UNITY_FLASH foreach (KeyValuePair<Transform, UINode> child in mChildren) { UINode pc = child.Value; #else for (int i = 0, imax = mChildren.Count; i < imax; ++i) { UINode pc = (UINode)mChildren[i]; #endif if (pc.widget != null) { // If the change flag has not yet been determined... if (pc.changeFlag == -1) pc.changeFlag = GetChangeFlag(pc); // Is the widget visible? int visibleFlag = (mCheckVisibility || pc.changeFlag == 1) ? (IsVisible(pc.widget) ? 1 : 0) : pc.visibleFlag; // If visibility changed, mark the node as changed as well if (pc.visibleFlag != visibleFlag) pc.changeFlag = 1; // If the node has changed and the widget is visible (or was visible before) if (pc.changeFlag == 1 && (visibleFlag == 1 || pc.visibleFlag != 0)) { // Update the visibility flag pc.visibleFlag = visibleFlag; Material mat = pc.widget.material; // Add this material to the list of changed materials if (!mChanged.Contains(mat)) mChanged.Add(mat); } } } } mCheckVisibility = false; } /// <summary> /// Update all widgets and rebuild their geometry if necessary. /// </summary> void UpdateWidgets () { #if UNITY_FLASH foreach (KeyValuePair<Transform, UINode> c in mChildren) { UINode pc = c.Value; #else for (int i = 0, imax = mChildren.Count; i < imax; ++i) { UINode pc = (UINode)mChildren[i]; #endif UIWidget w = pc.widget; // If the widget is visible, update it if (pc.visibleFlag == 1 && w != null && w.UpdateGeometry(ref mWorldToLocal, (pc.changeFlag == 1), generateNormals)) { // We will need to refill this buffer if (!mChanged.Contains(w.material)) { mChanged.Add(w.material); } } } } /// <summary> /// Update the clipping rect in the shaders and draw calls' positions. /// </summary> public void UpdateDrawcalls () { Vector4 range = Vector4.zero; if (mClipping != UIDrawCall.Clipping.None) { range = new Vector4(mClipRange.x, mClipRange.y, mClipRange.z * 0.5f, mClipRange.w * 0.5f); } if (range.z == 0f) range.z = Screen.width * 0.5f; if (range.w == 0f) range.w = Screen.height * 0.5f; RuntimePlatform platform = Application.platform; if (platform == RuntimePlatform.WindowsPlayer || platform == RuntimePlatform.WindowsWebPlayer || platform == RuntimePlatform.WindowsEditor) { range.x -= 0.5f; range.y += 0.5f; } Transform t = cachedTransform; for (int i = 0, imax = mDrawCalls.Count; i < imax; ++i) { UIDrawCall dc = mDrawCalls[i]; dc.clipping = mClipping; dc.clipRange = range; dc.clipSoftness = mClipSoftness; dc.depthPass = depthPass; // Set the draw call's transform to match the panel's. // Note that parenting directly to the panel causes unity to crash as soon as you hit Play. Transform dt = dc.transform; dt.position = t.position; dt.rotation = t.rotation; dt.localScale = t.lossyScale; } } /// <summary> /// Set the draw call's geometry responsible for the specified material. /// </summary> void Fill (Material mat) { // Cleanup deleted widgets for (int i = mWidgets.Count; i > 0; ) if (mWidgets[--i] == null) mWidgets.RemoveAt(i); // Fill the buffers for the specified material for (int i = 0, imax = mWidgets.Count; i < imax; ++i) { UIWidget w = mWidgets[i]; if (w.visibleFlag == 1 && w.material == mat) { UINode node = GetNode(w.cachedTransform); if (node != null) { if (generateNormals) w.WriteToBuffers(mVerts, mUvs, mCols, mNorms, mTans); else w.WriteToBuffers(mVerts, mUvs, mCols, null, null); } else { Debug.LogError("No transform found for " + NGUITools.GetHierarchy(w.gameObject), this); } } } if (mVerts.size > 0) { // Rebuild the draw call's mesh UIDrawCall dc = GetDrawCall(mat, true); dc.depthPass = depthPass; dc.Set(mVerts, generateNormals ? mNorms : null, generateNormals ? mTans : null, mUvs, mCols); } else { // There is nothing to draw for this material -- eliminate the draw call UIDrawCall dc = GetDrawCall(mat, false); if (dc != null) { mDrawCalls.Remove(dc); NGUITools.DestroyImmediate(dc.gameObject); } } // Cleanup mVerts.Clear(); mNorms.Clear(); mTans.Clear(); mUvs.Clear(); mCols.Clear(); } /// <summary> /// Main update function /// </summary> void LateUpdate () { UpdateTransformMatrix(); UpdateTransforms(); // Always move widgets to the panel's layer if (mLayer != gameObject.layer) { mLayer = gameObject.layer; UICamera uic = UICamera.FindCameraForLayer(mLayer); mCam = (uic != null) ? uic.cachedCamera : NGUITools.FindCameraForLayer(mLayer); SetChildLayer(cachedTransform, mLayer); for (int i = 0, imax = drawCalls.Count; i < imax; ++i) mDrawCalls[i].gameObject.layer = mLayer; } UpdateWidgets(); // If the depth has changed, we need to re-sort the widgets if (mDepthChanged) { mDepthChanged = false; mWidgets.Sort(UIWidget.CompareFunc); } // Fill the draw calls for all of the changed materials for (int i = 0, imax = mChanged.Count; i < imax; ++i) Fill(mChanged[i]); // Update the clipping rects UpdateDrawcalls(); mChanged.Clear(); mRebuildAll = false; #if UNITY_EDITOR mScreenSize = new Vector2(Screen.width, Screen.height); #endif } #if UNITY_EDITOR /// <summary> /// Draw a visible pink outline for the clipped area. /// </summary> void OnDrawGizmos () { if (mDebugInfo == DebugInfo.Gizmos && mClipping != UIDrawCall.Clipping.None) { Vector2 size = new Vector2(mClipRange.z, mClipRange.w); if (size.x == 0f) size.x = mScreenSize.x; if (size.y == 0f) size.y = mScreenSize.y; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.color = Color.magenta; Gizmos.DrawWireCube(new Vector2(mClipRange.x, mClipRange.y), size); } }
void Start() { _previousLocalToWorld = transform.localToWorldMatrix; }
public void Render(GraphicsDevice gd, CommandList cl, SceneContext sc, RenderPasses renderPass, SpriteModelResourceContainer modelResource, ref SpriteModelRenderData renderData) { if (renderData.Shared.RenderMode == RenderMode.Glow) { renderData.Shared.RenderAmount = GlowBlend(ref renderData.Shared, sc.ViewState); } //Don't render if blend is 0 (even if blend were ignored below) if (renderData.Shared.RenderAmount == 0) { return; } var blend = renderData.Shared.RenderMode != RenderMode.Normal ? renderData.Shared.RenderAmount : 255; //TODO: glow sprite visibility testing var angles = GetSpriteAngles(ref renderData.Shared, modelResource.SpriteModel.SpriteFile.Type, sc.ViewState); angles = VectorUtils.ToRadians(angles); var wai = new WorldAndInverse(); var anglesWithoutYaw = angles; anglesWithoutYaw.Y = 0; wai.World = Matrix4x4.CreateScale(renderData.Shared.Scale) * WorldAndInverse.CreateRotationMatrix(anglesWithoutYaw) * WorldAndInverse.CreateRotationMatrix(new Vector3(0, angles.Y, 0)) * Matrix4x4.CreateTranslation(renderData.Shared.Origin); wai.InverseWorld = VdUtilities.CalculateInverseTranspose(ref wai.World); //var wai = new WorldAndInverse(renderData.Origin, angles, renderData.Scale); sc.UpdateWorldAndInverseBuffer(cl, ref wai); var alpha = 255; switch (renderData.Shared.RenderMode) { case RenderMode.Normal: case RenderMode.TransTexture: case RenderMode.TransAlpha: alpha = blend; break; } var renderColor = new Vector4(CalculateSpriteColor(ref renderData.Shared, blend), alpha) / 255.0f; cl.UpdateBuffer(modelResource.RenderColorBuffer, 0, ref renderColor); renderData.Frame = Math.Clamp((int)renderData.Frame, 0, modelResource.VertexBuffers.Length - 1); var frameBuffer = modelResource.VertexBuffers[(int)renderData.Frame]; var pipeline = Pipelines[renderData.Shared.RenderMode]; cl.SetVertexBuffer(0, frameBuffer); cl.SetIndexBuffer(modelResource.IndexBuffer, IndexFormat.UInt16); cl.SetPipeline(pipeline); cl.SetGraphicsResourceSet(0, modelResource.ResourceSet); cl.DrawIndexed((uint)SPRResourceUtils.Indices.Length, 1, 0, 0, 0); }
public override IEnumerator RunJob() { Debug.Log("*************************** CoroutineJobLocalize On-Server ***************************"); byte[] capture = new byte[width * height + 1024]; Task<(string, icvCaptureInfo)> t = Task.Run(() => { icvCaptureInfo info = Immersal.Core.CaptureImage(capture, capture.Length, pixels, width, height, 1); return (Convert.ToBase64String(capture, 0, info.captureSize), info); }); while (!t.IsCompleted) { yield return null; } string encodedImage = t.Result.Item1; icvCaptureInfo captureInfo = t.Result.Item2; SDKLocalizeRequest imageRequest = new SDKLocalizeRequest(); imageRequest.token = this.token; imageRequest.fx = intrinsics.x; imageRequest.fy = intrinsics.y; imageRequest.ox = intrinsics.z; imageRequest.oy = intrinsics.w; imageRequest.b64 = encodedImage; int n = pcr.Count; imageRequest.mapIds = new SDKMapId[n]; int count = 0; foreach (int id in pcr.Keys) { imageRequest.mapIds[count] = new SDKMapId(); imageRequest.mapIds[count++].id = id; } string jsonString = JsonUtility.ToJson(imageRequest); using (UnityWebRequest request = UnityWebRequest.Put(string.Format(URL_FORMAT, this.server, "17"), jsonString)) { request.method = UnityWebRequest.kHttpVerbPOST; request.useHttpContinue = false; request.SetRequestHeader("Content-Type", "application/json"); request.SetRequestHeader("Accept", "application/json"); yield return request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) { Debug.Log(request.error); } else if (request.responseCode == (long)HttpStatusCode.OK) { SDKLocalizeResult result = JsonUtility.FromJson<SDKLocalizeResult>(request.downloadHandler.text); if (result.success) { Matrix4x4 cloudSpace = Matrix4x4.identity; cloudSpace.m00 = result.r00; cloudSpace.m01 = result.r01; cloudSpace.m02 = result.r02; cloudSpace.m03 = result.px; cloudSpace.m10 = result.r10; cloudSpace.m11 = result.r11; cloudSpace.m12 = result.r12; cloudSpace.m13 = result.py; cloudSpace.m20 = result.r20; cloudSpace.m21 = result.r21; cloudSpace.m22 = result.r22; cloudSpace.m23 = result.pz; Matrix4x4 trackerSpace = Matrix4x4.TRS(position, rotation, Vector3.one); stats.locSucc++; Debug.Log("*************************** On-Server Localization Succeeded ***************************"); Debug.Log("fc 4x4\n" + cloudSpace + "\n" + "ft 4x4\n" + trackerSpace); Matrix4x4 m = trackerSpace * (cloudSpace.inverse); foreach (KeyValuePair<int, PointCloudRenderer> p in pcr) { if (p.Key == result.map) { p.Value.go.transform.position = m.GetColumn(3); p.Value.go.transform.rotation = m.rotation; break; } } Debug.Log(result.error); } else { stats.locFail++; Debug.Log("*************************** On-Server Localization Failed ***************************"); } } } }
////////////////////////////////////////////////////////////////SSAO Function//////////////////////////////////////////////////////////////// private void UpdateVariable_SSAO() { //---------------------------------------------------------------------------------- worldToCameraMatrix = RenderCamera.worldToCameraMatrix; GTAOMaterial.SetMatrix(_WorldToCameraMatrix_ID, worldToCameraMatrix); GTAOMaterial.SetMatrix(_CameraToWorldMatrix_ID, worldToCameraMatrix.inverse); projectionMatrix = GL.GetGPUProjectionMatrix(RenderCamera.projectionMatrix, false); GTAOMaterial.SetMatrix(_ProjectionMatrix_ID, projectionMatrix); View_ProjectionMatrix = projectionMatrix * worldToCameraMatrix; GTAOMaterial.SetMatrix(_View_ProjectionMatrix_ID, View_ProjectionMatrix); GTAOMaterial.SetMatrix(_Inverse_View_ProjectionMatrix_ID, View_ProjectionMatrix.inverse); GTAOMaterial.SetMatrix(_LastFrameViewProjectionMatrix_ID, LastFrameViewProjectionMatrix); //---------------------------------------------------------------------------------- GTAOMaterial.SetFloat(_AO_DirSampler_ID, DirSampler); GTAOMaterial.SetFloat(_AO_SliceSampler_ID, SliceSampler); GTAOMaterial.SetFloat(_AO_Intensity_ID, Intensity); GTAOMaterial.SetFloat(_AO_Radius_ID, Radius); GTAOMaterial.SetFloat(_AO_Power_ID, Power); GTAOMaterial.SetFloat(_AO_Sharpeness_ID, Sharpeness); GTAOMaterial.SetFloat(_AO_TemporalScale_ID, TemporalScale); GTAOMaterial.SetFloat(_AO_TemporalResponse_ID, TemporalResponse); GTAOMaterial.SetInt(_AO_MultiBounce_ID, MultiBounce ? 1 : 0); //---------------------------------------------------------------------------------- float fovRad = RenderCamera.fieldOfView * Mathf.Deg2Rad; float invHalfTanFov = 1 / Mathf.Tan(fovRad * 0.5f); Vector2 focalLen = new Vector2(invHalfTanFov * ((float)RenderResolution.y / (float)RenderResolution.x), invHalfTanFov); Vector2 invFocalLen = new Vector2(1 / focalLen.x, 1 / focalLen.y); GTAOMaterial.SetVector(_AO_UVToView_ID, new Vector4(2 * invFocalLen.x, 2 * invFocalLen.y, -1 * invFocalLen.x, -1 * invFocalLen.y)); //---------------------------------------------------------------------------------- float projScale; projScale = (float)RenderResolution.y / (Mathf.Tan(fovRad * 0.5f) * 2) * 0.5f; GTAOMaterial.SetFloat(_AO_HalfProjScale_ID, projScale); //---------------------------------------------------------------------------------- oneOverSize_Size = new Vector4(1 / (float)RenderResolution.x, 1 / (float)RenderResolution.y, (float)RenderResolution.x, (float)RenderResolution.y); GTAOMaterial.SetVector(_AO_RT_TexelSize_ID, oneOverSize_Size); //---------------------------------------------------------------------------------- float temporalRotation = m_temporalRotations[m_sampleStep % 6]; float temporalOffset = m_spatialOffsets[(m_sampleStep / 6) % 4]; GTAOMaterial.SetFloat(_AO_TemporalDirections_ID, temporalRotation / 360); GTAOMaterial.SetFloat(_AO_TemporalOffsets_ID, temporalOffset); m_sampleStep++; //---------------------------------------------------------------------------------- if (AO_BentNormal_RT[0] != null) { AO_BentNormal_RT[0].Release(); } if (AO_BentNormal_RT[1] != null) { AO_BentNormal_RT[1].Release(); } AO_BentNormal_RT[0] = new RenderTexture((int)RenderResolution.x, (int)RenderResolution.y, 0, RenderTextureFormat.RGHalf); AO_BentNormal_RT[1] = new RenderTexture((int)RenderResolution.x, (int)RenderResolution.y, 0, RenderTextureFormat.ARGBHalf); AO_BentNormal_ID[0] = AO_BentNormal_RT[0].colorBuffer; AO_BentNormal_ID[1] = AO_BentNormal_RT[1].colorBuffer; //---------------------------------------------------------------------------------- Vector2 currentCameraSize = RenderResolution; if (CameraSize != currentCameraSize) { CameraSize = currentCameraSize; //---------------------------------------------------------------------------------- if (Prev_RT != null) { Prev_RT.Release(); } Prev_RT = new RenderTexture((int)RenderResolution.x, (int)RenderResolution.y, 0, RenderTextureFormat.RGHalf); Prev_RT.filterMode = FilterMode.Point; } }
void OnGUI() { var guiScale = new Vector3(Screen.width / 800.0f, Screen.height / 600.0f, 1.0f); GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, guiScale); GUILayout.Space(20); GUILayout.BeginHorizontal(); GUILayout.Space(20); GUILayout.BeginVertical(); // Open File Samples if (GUILayout.Button("Open File")) { WriteResult(StandaloneFileBrowser.OpenFilePanel("Open File", "", "", false)); } GUILayout.Space(5); if (GUILayout.Button("Open File Async")) { StandaloneFileBrowser.OpenFilePanelAsync("Open File", "", "", false, (string[] paths) => { WriteResult(paths); }); } GUILayout.Space(5); if (GUILayout.Button("Open File Multiple")) { WriteResult(StandaloneFileBrowser.OpenFilePanel("Open File", "", "", true)); } GUILayout.Space(5); if (GUILayout.Button("Open File Extension")) { WriteResult(StandaloneFileBrowser.OpenFilePanel("Open File", "", "txt", true)); } GUILayout.Space(5); if (GUILayout.Button("Open File Directory")) { WriteResult(StandaloneFileBrowser.OpenFilePanel("Open File", Application.dataPath, "", true)); } GUILayout.Space(5); if (GUILayout.Button("Open File Filter")) { var extensions = new [] { new ExtensionFilter("Image Files", "png", "jpg", "jpeg" ), new ExtensionFilter("Sound Files", "mp3", "wav" ), new ExtensionFilter("All Files", "*" ), }; WriteResult(StandaloneFileBrowser.OpenFilePanel("Open File", "", extensions, true)); } GUILayout.Space(15); // Open Folder Samples if (GUILayout.Button("Open Folder")) { var paths = StandaloneFileBrowser.OpenFolderPanel("Select Folder", "", true); WriteResult(paths); } GUILayout.Space(5); if (GUILayout.Button("Open Folder Async")) { StandaloneFileBrowser.OpenFolderPanelAsync("Select Folder", "", true, (string[] paths) => { WriteResult(paths); }); } GUILayout.Space(5); if (GUILayout.Button("Open Folder Directory")) { var paths = StandaloneFileBrowser.OpenFolderPanel("Select Folder", Application.dataPath, true); WriteResult(paths); } GUILayout.Space(15); // Save File Samples if (GUILayout.Button("Save File")) { _path = StandaloneFileBrowser.SaveFilePanel("Save File", "", "", ""); } GUILayout.Space(5); if (GUILayout.Button("Save File Async")) { StandaloneFileBrowser.SaveFilePanelAsync("Save File", "", "", "", (string path) => { WriteResult(path); }); } GUILayout.Space(5); if (GUILayout.Button("Save File Default Name")) { _path = StandaloneFileBrowser.SaveFilePanel("Save File", "", "MySaveFile", ""); } GUILayout.Space(5); if (GUILayout.Button("Save File Default Name Ext")) { _path = StandaloneFileBrowser.SaveFilePanel("Save File", "", "MySaveFile", "dat"); } GUILayout.Space(5); if (GUILayout.Button("Save File Directory")) { _path = StandaloneFileBrowser.SaveFilePanel("Save File", Application.dataPath, "", ""); } GUILayout.Space(5); if (GUILayout.Button("Save File Filter")) { // Multiple save extension filters with more than one extension support. var extensionList = new [] { new ExtensionFilter("Binary", "bin"), new ExtensionFilter("Text", "txt"), }; _path = StandaloneFileBrowser.SaveFilePanel("Save File", "", "MySaveFile", extensionList); } GUILayout.EndVertical(); GUILayout.Space(20); GUILayout.Label(_path); GUILayout.EndHorizontal(); }
void DrawCurves() { if (m_Stopped) { return; } MarkDirtyRepaint(); // draw matrix var debugRect = m_DebugUI.m_DebugDrawingBox.worldBound; var clippedDebugRect = k_BoxWorldclip(m_DebugUI.m_DebugDrawingBox); var windowRect = panel.InternalGetGUIView().position; var trans = new Vector4(debugRect.x / windowRect.width, (windowRect.height - (debugRect.y + debugRect.height)) / windowRect.height, 0, 0); var scale = new Vector3(debugRect.width / windowRect.width, debugRect.height / windowRect.height, 0); // clip matrix var clippedScale = new Vector3(windowRect.width / clippedDebugRect.width, windowRect.height / clippedDebugRect.height, 0); var clippedTrans = new Vector3(-clippedDebugRect.x / clippedDebugRect.width, ((clippedDebugRect.y + clippedDebugRect.height) - windowRect.height) / clippedDebugRect.height); var baseChange = Matrix4x4.TRS(clippedTrans, Quaternion.identity, clippedScale); m_CurveMat.SetMatrix(m_ClippingMatrixId, baseChange); m_BarMat.SetMatrix(m_ClippingMatrixId, baseChange); // curves update var now = Time.time; bool shouldSample = (!m_Pause && (now - m_LastSampleTime > m_TimeBetweenDraw)) || (m_Pause && m_Step); m_Step = false; if (shouldSample) { m_LastSampleTime = now; } int i = 0; var curveData = GetCurvesData(); var TRS = Matrix4x4.TRS(trans, Quaternion.identity, scale); foreach (var vfxCurve in m_VFXCurves) { if (vfxCurve.toggle == null || vfxCurve.toggle.value == true) { if (shouldSample && m_DebugUI.m_VFX.HasSystem(vfxCurve.id)) { UpdateCurve(vfxCurve, curveData); } m_CurveMat.SetColor("_Color", GetColor(i)); m_CurveMat.SetPass(0); Graphics.DrawMeshNow(vfxCurve.curve.GetMesh(), TRS); } ++i; } // time bars creation if (shouldSample && (now - m_LastTimeBarDrawTime > s_TimeBarsInterval)) { m_LastTimeBarDrawTime = now; m_TimeBarsOffsets.Add(1); } // time bars update var xShift = 1.0f / (float)(m_MaxPoints - 1); Color timeBarColor = new Color(1, 0, 0, 0.5f).gamma; for (int j = 0; j < m_TimeBarsOffsets.Count(); ++j) { if (m_TimeBarsOffsets[j] < 0) { m_TimeBarsOffsets.RemoveAt(j); --j; continue; } m_BarMat.SetFloat("_AbscissaOffset", m_TimeBarsOffsets[j]); if (shouldSample) { m_TimeBarsOffsets[j] -= xShift; } if (m_ShouldDrawTimeBars) { m_BarMat.SetColor("_Color", timeBarColor); m_BarMat.SetPass(0); Graphics.DrawMeshNow(m_VerticalBar.GetMesh(), TRS); } } m_BarMat.SetFloat("_AbscissaOffset", 0); }
/// <summary> /// /// </summary> public static Vector3[] ToNormalsArray (IEnumerable <IEnumerable <Vector3> > normalsPerMeshes, IEnumerable <Matrix4x4> mtObjects, Matrix4x4 mtBaseInv) { var qNormal = from xy in (normalsPerMeshes, mtObjects).Zip((x, y) => (nms: x, mt: y)) let mt = mtBaseInv * xy.mt from nm in xy.nms select mt.MultiplyVector(nm) ; return(qNormal.ToArray()); }
public bool UpdateSpriteShapeParameters() { bool carpet = !spline.isOpenEnded; bool smartSprite = true; bool adaptiveUV = m_AdaptiveUV; bool stretchUV = m_StretchUV; bool spriteBorders = false; uint fillScale = 0; uint splineDetail = (uint)m_SplineDetail; float borderPivot = 0f; float angleThreshold = (m_CornerAngleThreshold >= 0 && m_CornerAngleThreshold < 90) ? m_CornerAngleThreshold : 89.9999f; Texture2D fillTexture = null; Matrix4x4 transformMatrix = Matrix4x4.identity; if (spriteShape) { if (worldSpaceUVs) transformMatrix = transform.localToWorldMatrix; fillTexture = spriteShape.fillTexture; fillScale = stretchUV ? (uint)stretchTiling : (uint)fillPixelsPerUnit; borderPivot = spriteShape.fillOffset; spriteBorders = spriteShape.useSpriteBorders; // If Corners are enabled, set smart-sprite to false. if (spriteShape.cornerSprites.Count > 0) smartSprite = false; } else { #if UNITY_EDITOR fillTexture = UnityEditor.EditorGUIUtility.whiteTexture; fillScale = 100; #endif } bool changed = m_ActiveShapeParameters.adaptiveUV != adaptiveUV || m_ActiveShapeParameters.angleThreshold != angleThreshold || m_ActiveShapeParameters.borderPivot != borderPivot || m_ActiveShapeParameters.carpet != carpet || m_ActiveShapeParameters.fillScale != fillScale || m_ActiveShapeParameters.fillTexture != fillTexture || m_ActiveShapeParameters.smartSprite != smartSprite || m_ActiveShapeParameters.splineDetail != splineDetail || m_ActiveShapeParameters.spriteBorders != spriteBorders || m_ActiveShapeParameters.transform != transformMatrix || m_ActiveShapeParameters.stretchUV != stretchUV; m_ActiveShapeParameters.adaptiveUV = adaptiveUV; m_ActiveShapeParameters.stretchUV = stretchUV; m_ActiveShapeParameters.angleThreshold = angleThreshold; m_ActiveShapeParameters.borderPivot = borderPivot; m_ActiveShapeParameters.carpet = carpet; m_ActiveShapeParameters.fillScale = fillScale; m_ActiveShapeParameters.fillTexture = fillTexture; m_ActiveShapeParameters.smartSprite = smartSprite; m_ActiveShapeParameters.splineDetail = splineDetail; m_ActiveShapeParameters.spriteBorders = spriteBorders; m_ActiveShapeParameters.transform = transformMatrix; return changed; }
void UpdateCurveMesh() { textComponent.ForceMeshUpdate(); TMP_TextInfo textInfo = textComponent.textInfo; int characterCount = textInfo.characterCount; if (characterCount == 0) { return; } Vector3 baseline = new Vector3(); Vector3 prevAngleDirection = new Vector3(); Vector3 prevOffsetToMidBaseline = new Vector3(); Vector3[] vertices; Matrix4x4 matrix; float defaultBaseLine = 0; float maxBaseLine = float.MinValue; float minBaseLine = float.MaxValue; bool isFirst = true; for (int i = 0; i < characterCount; i++) { if (!textInfo.characterInfo[i].isVisible) { continue; } int vertexIndex = textInfo.characterInfo[i].vertexIndex; int materialIndex = textInfo.characterInfo[i].materialReferenceIndex; vertices = textInfo.meshInfo[materialIndex].vertices; //文字の真ん中の点と文字の基準となるベースラインの高さを取得 Vector3 offsetToMidBaseline = new Vector2((vertices[vertexIndex + 0].x + vertices[vertexIndex + 2].x) / 2, textInfo.characterInfo[i].baseLine); //文字の中央の下が原点となるように頂点を移動(これから回転と移動をさせるため) vertices[vertexIndex + 0] += -offsetToMidBaseline; vertices[vertexIndex + 1] += -offsetToMidBaseline; vertices[vertexIndex + 2] += -offsetToMidBaseline; vertices[vertexIndex + 3] += -offsetToMidBaseline; //曲線の傾き(agnle)の計算 float x0 = (float)(i + 1) / (characterCount + 1); float x1 = x0 + 0.0001f; float y0 = vertexCurve.Evaluate(x0); float y1 = vertexCurve.Evaluate(x1); Vector3 horizontal = new Vector3(1, 0, 0); Vector3 tangent = new Vector3(0.0001f, (y1 - y0)); Vector3 angleDirection = tangent.normalized; float angle = Mathf.Acos(Vector3.Dot(horizontal, angleDirection)) * Mathf.Rad2Deg; Vector3 cross = Vector3.Cross(horizontal, tangent); angle = cross.z > 0 ? angle : 360 - angle; //angle回転させた頂点位置の計算 matrix = Matrix4x4.Rotate(Quaternion.Euler(0, 0, angle)); vertices[vertexIndex + 0] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 0]); vertices[vertexIndex + 1] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 1]); vertices[vertexIndex + 2] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 2]); vertices[vertexIndex + 3] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 3]); //文字間の計算 float characterSpace; if (isFirst) { baseline = offsetToMidBaseline; defaultBaseLine = baseline.y; characterSpace = 0; isFirst = false; } else { characterSpace = (offsetToMidBaseline - prevOffsetToMidBaseline).magnitude; } prevOffsetToMidBaseline = offsetToMidBaseline; //文字位置を計算して移動 baseline = baseline + (angleDirection + prevAngleDirection).normalized * characterSpace; vertices[vertexIndex + 0] += baseline; vertices[vertexIndex + 1] += baseline; vertices[vertexIndex + 2] += baseline; vertices[vertexIndex + 3] += baseline; prevAngleDirection = angleDirection; minBaseLine = Mathf.Min(minBaseLine, baseline.y); maxBaseLine = Mathf.Max(maxBaseLine, baseline.y); } //揃えの計算 if (hAlignment != TextAlignment.Left || vAlignment != TextVAlignment.Base) { float hOffset = 0; if (hAlignment == TextAlignment.Center) { hOffset = (prevOffsetToMidBaseline.x - baseline.x) * 0.5f; } else if (hAlignment == TextAlignment.Right) { hOffset = (prevOffsetToMidBaseline.x - baseline.x); } float vOffset = 0; if (vAlignment == TextVAlignment.Bottom) { vOffset = defaultBaseLine - minBaseLine; } else if (vAlignment == TextVAlignment.Top) { vOffset = defaultBaseLine - maxBaseLine; } Vector3 alignOffset = new Vector3(hOffset, vOffset, 0); for (int i = 0; i < characterCount; i++) { if (!textInfo.characterInfo[i].isVisible) { continue; } int vertexIndex = textInfo.characterInfo[i].vertexIndex; int materialIndex = textInfo.characterInfo[i].materialReferenceIndex; vertices = textInfo.meshInfo[materialIndex].vertices; vertices[vertexIndex + 0] += alignOffset; vertices[vertexIndex + 1] += alignOffset; vertices[vertexIndex + 2] += alignOffset; vertices[vertexIndex + 3] += alignOffset; } } textComponent.UpdateVertexData(); }
/// <summary> /// 反転(スケールの一部がマイナス)メッシュであれば、三角インデックスを逆順にする。 /// </summary> public static IEnumerable <int> ReverseEvery3_IfMinusScale(this IEnumerable <int> indices, Matrix4x4 mtObject) { if (mtObject.IsMuinusScale()) { return(reverseEvery3_(indices)); } return(indices); IEnumerable <int> reverseEvery3_(IEnumerable <int> indecies_) { using (var e = indecies_.GetEnumerator()) { while (e.MoveNext()) { var i0 = e.Current; e.MoveNext(); var i1 = e.Current; e.MoveNext(); var i2 = e.Current; yield return(i2); //210でもいい? yield return(i1); yield return(i0); } } } }
// po 1-1822973892 // TODO: If we draw like warps do we know if we are the current edited script? public virtual void DrawGizmo(MegaModContext context) { tm = Matrix4x4.identity; MegaMatrix.Translate(ref tm, context.Offset); invtm = tm.inverse; if (!Prepare(context)) { return; } Vector3 min = context.bbox.min; Vector3 max = context.bbox.max; Matrix4x4 gtm = Matrix4x4.identity; Vector3 pos = gizmoPos; pos.x = -pos.x; pos.y = -pos.y; pos.z = -pos.z; Vector3 scl = gizmoScale; scl.x = 1.0f - (scl.x - 1.0f); scl.y = 1.0f - (scl.y - 1.0f); gtm.SetTRS(pos, Quaternion.Euler(gizmoRot), scl); // put sourceObj into context if (context.mod.sourceObj != null) { Gizmos.matrix = context.mod.sourceObj.transform.localToWorldMatrix * gtm; } else { Gizmos.matrix = context.go.transform.localToWorldMatrix * gtm; } //Gizmos.color = ModCol(); //Color.yellow; corners[0] = new Vector3(min.x, min.y, min.z); corners[1] = new Vector3(min.x, max.y, min.z); corners[2] = new Vector3(max.x, max.y, min.z); corners[3] = new Vector3(max.x, min.y, min.z); corners[4] = new Vector3(min.x, min.y, max.z); corners[5] = new Vector3(min.x, max.y, max.z); corners[6] = new Vector3(max.x, max.y, max.z); corners[7] = new Vector3(max.x, min.y, max.z); DrawEdge(corners[0], corners[1]); DrawEdge(corners[1], corners[2]); DrawEdge(corners[2], corners[3]); DrawEdge(corners[3], corners[0]); DrawEdge(corners[4], corners[5]); DrawEdge(corners[5], corners[6]); DrawEdge(corners[6], corners[7]); DrawEdge(corners[7], corners[4]); DrawEdge(corners[0], corners[4]); DrawEdge(corners[1], corners[5]); DrawEdge(corners[2], corners[6]); DrawEdge(corners[3], corners[7]); ExtraGizmo(context); }
/// <summary> /// /// </summary> public static Vector3[] ToVerticesArray (IEnumerable <IEnumerable <Vector3> > verticesPerMeshes, IEnumerable <Matrix4x4> mtObjects, Matrix4x4 mtBaseInv) { var qVertex = from xy in (verticesPerMeshes, mtObjects).Zip((x, y) => (vtxs: x, mt: y)) let mt = mtBaseInv * xy.mt from vtx in xy.vtxs select mt.MultiplyPoint3x4(vtx) ; return(qVertex.ToArray()); }
/// <summary> /// Preform the first step of clipping, which is unpacking the mesh on the main thread /// </summary> /// <param name="mesh"></param> /// <param name="clippingPlaneSet"></param> /// <returns></returns> private static Task <List <MeshPoly> > ClipUnpack(Mesh mesh, ClippingPlaneSet clippingPlaneSet, Matrix4x4 worldToMeshSpace) { List <MeshPoly> output = new List <MeshPoly>(); Vector3[] vertices = mesh.vertices; Vector2[] uvs = mesh.uv; int[] triangles = mesh.triangles; Vector3[] normals = mesh.normals; Vector4[] tangents = mesh.tangents; Color[] colors = mesh.colors; return(Task.Run(() => { return ClipEachPolygonByEachClippingPlane( ArrayToPolys(vertices, uvs, triangles, normals, tangents, colors), clippingPlaneSet, worldToMeshSpace); })); }
static string WriteObjContents(string name, IEnumerable <Model> models, Dictionary <Material, string> materialMap, ObjOptions options) { // Empty names in OBJ groups can crash some 3d programs (meshlab) if (string.IsNullOrEmpty(name)) { name = "ProBuilderModel"; } StringBuilder sb = new StringBuilder(); SemVer version; if (Version.TryGetPackageVersion(out version)) { sb.AppendLine("# ProBuilder " + version.MajorMinorPatch); } else { sb.AppendLine("# ProBuilder"); } sb.AppendLine("# https://unity3d.com/unity/features/worldbuilding/probuilder"); sb.AppendLine(string.Format("# {0}", System.DateTime.Now)); sb.AppendLine(); sb.AppendLine(string.Format("mtllib ./{0}.mtl", name.Replace(" ", "_"))); sb.AppendLine(string.Format("o {0}", name)); sb.AppendLine(); // obj orders indices 1 indexed int positionOffset = 1; int normalOffset = 1; int textureOffset = 1; bool reverseWinding = options.handedness == ObjOptions.Handedness.Right; float handedness = options.handedness == ObjOptions.Handedness.Left ? 1f : -1f; foreach (Model model in models) { int subMeshCount = model.submeshCount; Matrix4x4 matrix = options.applyTransforms ? model.matrix : Matrix4x4.identity; int vertexCount = model.vertexCount; Vector3[] positions; Color[] colors; Vector2[] textures0; Vector3[] normals; Vector4[] tangent; Vector2[] uv2; List <Vector4> uv3; List <Vector4> uv4; MeshArrays attribs = MeshArrays.Position | MeshArrays.Normal | MeshArrays.Texture0; if (options.vertexColors) { attribs = attribs | MeshArrays.Color; } Vertex.GetArrays(model.vertices, out positions, out colors, out textures0, out normals, out tangent, out uv2, out uv3, out uv4, attribs); // Can skip this entirely if handedness matches Unity & not applying transforms. // matrix is set to identity if not applying transforms. if (options.handedness != ObjOptions.Handedness.Left || options.applyTransforms) { for (int i = 0; i < vertexCount; i++) { if (positions != null) { positions[i] = matrix.MultiplyPoint3x4(positions[i]); positions[i].x *= handedness; } if (normals != null) { normals[i] = matrix.MultiplyVector(normals[i]); normals[i].x *= handedness; } } } sb.AppendLine(string.Format("g {0}", model.name)); Dictionary <int, int> positionIndexMap; var positionCount = AppendPositions(sb, positions, colors, true, options.vertexColors, out positionIndexMap); sb.AppendLine(); Dictionary <int, int> textureIndexMap; var textureCount = AppendArrayVec2(sb, textures0, "vt", true, out textureIndexMap); sb.AppendLine(); Dictionary <int, int> normalIndexMap; var normalCount = AppendArrayVec3(sb, normals, "vn", true, out normalIndexMap); sb.AppendLine(); // Material assignment for (int submeshIndex = 0; submeshIndex < subMeshCount; submeshIndex++) { Submesh submesh = model.submeshes[submeshIndex]; string materialName = ""; if (materialMap.TryGetValue(model.materials[submeshIndex], out materialName)) { sb.AppendLine(string.Format("usemtl {0}", materialName)); } else { sb.AppendLine(string.Format("usemtl {0}", "null")); } int[] indexes = submesh.m_Indexes; int inc = submesh.m_Topology == MeshTopology.Quads ? 4 : 3; int inc1 = inc - 1; int o0 = reverseWinding ? inc1 : 0; int o1 = reverseWinding ? inc1 - 1 : 1; int o2 = reverseWinding ? inc1 - 2 : 2; int o3 = reverseWinding ? inc1 - 3 : 3; for (int ff = 0; ff < indexes.Length; ff += inc) { int p0 = positionIndexMap[indexes[ff + o0]] + positionOffset; int p1 = positionIndexMap[indexes[ff + o1]] + positionOffset; int p2 = positionIndexMap[indexes[ff + o2]] + positionOffset; int t0 = textureIndexMap[indexes[ff + o0]] + textureOffset; int t1 = textureIndexMap[indexes[ff + o1]] + textureOffset; int t2 = textureIndexMap[indexes[ff + o2]] + textureOffset; int n0 = normalIndexMap[indexes[ff + o0]] + normalOffset; int n1 = normalIndexMap[indexes[ff + o1]] + normalOffset; int n2 = normalIndexMap[indexes[ff + o2]] + normalOffset; if (inc == 4) { int p3 = positionIndexMap[indexes[ff + o3]] + positionOffset; int n3 = normalIndexMap[indexes[ff + o3]] + normalOffset; int t3 = textureIndexMap[indexes[ff + o3]] + textureOffset; sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "f {0}/{4}/{8} {1}/{5}/{9} {2}/{6}/{10} {3}/{7}/{11}", p0, p1, p2, p3, t0, t1, t2, t3, n0, n1, n2, n3 )); } else { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "f {0}/{3}/{6} {1}/{4}/{7} {2}/{5}/{8}", p0, p1, p2, t0, t1, t2, n0, n1, n2 )); } } sb.AppendLine(); } positionOffset += positionCount; normalOffset += normalCount; textureOffset += textureCount; } return(sb.ToString()); }
private static MeshPoly ClipPolyByPlane(MeshPoly poly, MeshClippingPlane plane, Matrix4x4 worldToMeshSpace, List <(Vector3 a, Vector3 b)> newEdges)
//TODO:destset for binding must be variable //TODO: ADD REFAULT MAT IF NO MAT DEFINED public abstract void RenderNode(CommandBuffer cmd, PipelineLayout pipelineLayout, Node node, Matrix4x4 currentTransform, bool shadowPass = false);
void Update() { if (m_active && m_mesh != null && m_material != null) { UpdateCameraPosition(); m_camera.enabled = true; m_angle = (m_angle + m_rotationSpeed * Time.deltaTime) % 360.0f; Vector3 pos = m_mesh.bounds.center; pos.y = 0; Matrix4x4 matrix = Matrix4x4.TRS(pos, Quaternion.identity, Vector3.one) * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, m_angle, 0), Vector3.one); Graphics.DrawMesh(m_mesh, matrix, m_material, gameObject.layer); } else { m_camera.enabled = false; } }
/// <summary> /// Create a task to clip a new mesh. /// </summary> /// <param name="mesh"></param> /// <param name="clippingPlaneSet"></param> /// <param name="source"></param> /// <returns></returns> public static Task <Mesh> Clip(Mesh mesh, ClippingPlaneSet clippingPlaneSet, Matrix4x4 worldToMeshSpace, Mesh source = null) { return(ClipUnpack(mesh, clippingPlaneSet, worldToMeshSpace).ThenOnMainThread((x) => MeshPoly.ContructMesh(x, source))); }
VimSceneNode ITransformable3D<VimSceneNode>.Transform(Matrix4x4 mat) => new VimSceneNode(_Scene, _Source, Id, mat * Transform);
private static List <MeshPoly> ClipEachPolyByClippingPlane(List <MeshPoly> polys, MeshClippingPlane plane, Matrix4x4 worldToMeshSpace) { List <MeshPoly> output = new List <MeshPoly>(); List <(Vector3 a, Vector3 b)> newEdges = new List <(Vector3 a, Vector3 b)>(); foreach (var poly in polys) { var newPoly = ClipPolyByPlane(poly, plane, worldToMeshSpace, newEdges); if (newPoly.vertices.Count >= 3) { output.Add(newPoly); } } output.AddRange(ConstructPolysFromEdges(newEdges, worldToMeshSpace.MultiplyVector(plane.normal))); return(output); }
internal void SetViewAndProjectionMatrix(Matrix4x4 viewMatrix, Matrix4x4 projectionMatrix) { m_ViewMatrix = viewMatrix; m_ProjectionMatrix = projectionMatrix; }
protected override void OnPluginPostSolve() { // We do actual emission after the solver has run for (var particleIndex = 0; particleIndex < m_Count; ++particleIndex) { var id = m_MixerData[particleIndex].emitVelocity.w; if (Mathf.Abs(id) < FluvioSettings.kEpsilon) { continue; } var system = Mathf.Abs(id - 1.0f) < FluvioSettings.kEpsilon ? fluidC : fluidD; m_MixerData[particleIndex].emitVelocity.w = 0; // Emit from particle systems var toSystemSpace = Matrix4x4.identity; var localTransform = system.transform; #if UNITY_5_5_OR_NEWER var simulationSpace = system.main.simulationSpace; var scalingMode = system.main.scalingMode; if (system.main.simulationSpace == ParticleSystemSimulationSpace.Custom) { var customSpace = system.main.customSimulationSpace; if (customSpace) { localTransform = customSpace; } } #else var simulationSpace = system.simulationSpace; #endif if (simulationSpace != ParticleSystemSimulationSpace.World) { #if UNITY_5_3_PLUS #if UNITY_5_5_OR_NEWER switch (system.main.scalingMode) #else switch (system.scalingMode) #endif { case ParticleSystemScalingMode.Hierarchy: toSystemSpace = localTransform.localToWorldMatrix; break; case ParticleSystemScalingMode.Local: toSystemSpace = Matrix4x4.TRS(localTransform.position, localTransform.rotation, localTransform.localScale); break; case ParticleSystemScalingMode.Shape: #endif toSystemSpace = Matrix4x4.TRS(localTransform.position, localTransform.rotation, Vector3.one); #if UNITY_5_3_PLUS break; } #endif } #if UNITY_5_3_PLUS var emitParams = new ParticleSystem.EmitParams { position = toSystemSpace.MultiplyPoint3x4(m_MixerData[particleIndex].emitPosition), velocity = toSystemSpace.MultiplyVector(m_MixerData[particleIndex].emitVelocity) }; system.Emit(emitParams, 1); #else system.Emit( toSystemSpace.MultiplyPoint3x4(m_MixerData[particleIndex].emitPosition), toSystemSpace.MultiplyVector(m_MixerData[particleIndex].emitVelocity), system.startSize, system.startLifetime, system.startColor); #endif } }