public void Init(int passId, Matrix viewProjMatrix, MyViewport viewport, MyGBuffer gbuffer) { m_viewProjMatrix = viewProjMatrix; m_viewport = viewport; m_gbuffer = gbuffer; Init(passId, "GBuffer", MyFrustumEnum.MainFrustum, MyPassIdResolver.GetGBufferPassIdx(PassId)); }
private float GetRotate(VRageMath.Vector3 axis) { if (!XUtils.Directions.Contains(axis)) { throw new Exception("Invalid axis vector used: " + axis); } VRageMath.Matrix local = new VRageMath.Matrix(); referenceBlock.Orientation.GetMatrix(out local); axis = VRageMath.Vector3.Transform(axis, local); float totalValue = 0; for (int i = 0; i < gyroscopeBlocks.Count; ++i) { IMyGyro gyro = gyroscopeBlocks[i] as IMyGyro; gyro.Orientation.GetMatrix(out local); VRageMath.Matrix toGyro = VRageMath.Matrix.Transpose(local); VRageMath.Vector3 transformedAxis = VRageMath.Vector3.Transform(axis, toGyro); GyroAction action = GyroAction.getActionAroundAxis(transformedAxis); float value = gyro.GetValue <float>(action.Name); totalValue += action.Reversed ? -value : value; } return(totalValue); }
public void UpdateThrusters(List <IMyTerminalBlock> blocks) { thrusterBlocks = new Dictionary <VRageMath.Vector3, List <IMyThrust> >(); VRageMath.Matrix toReference = new VRageMath.Matrix(); referenceBlock.Orientation.GetMatrix(out toReference); VRageMath.Matrix.Transpose(ref toReference, out toReference); VRageMath.Matrix tmp = new VRageMath.Matrix(); for (int i = 0; i < blocks.Count; ++i) { IMyTerminalBlock block = blocks[i]; if (block is IMyThrust) { block.Orientation.GetMatrix(out tmp); // The exhaust is directed to the Forward vector of the thruster, so it accelerates to Backward. VRageMath.Vector3 dir = VRageMath.Vector3.Transform(tmp.Backward, toReference); if (!thrusterBlocks.ContainsKey(dir)) { thrusterBlocks[dir] = new List <IMyThrust>(); } thrusterBlocks[dir].Add(block as IMyThrust); } } if (thrusterBlocks.Count == 0) { throw new Exception("There is no thruster within the given block list."); } }
private void SetupDrillSensor(VRageMath.Matrix fromReference, int id, VRageMath.BoundingBox bb) { // grid size in meters per block float gridSize = sensors[id].CubeGrid.GridSize; // matrix from grid coordinate system to sensor coordinate system VRageMath.Matrix toSensor = new VRageMath.Matrix(); sensors[id].Orientation.GetMatrix(out toSensor); // matrix is orthogonal => transposed matrix = inversed matrix VRageMath.Matrix.Transpose(ref toSensor, out toSensor); VRageMath.Vector3[] corners = bb.GetCorners(); VRageMath.Vector3 diffMax = corners[1] - sensors[id].Position; VRageMath.Vector3 diffMin = corners[7] - sensors[id].Position; List <VRageMath.Vector3> .Enumerator enumerator = XUtils.Directions.GetEnumerator(); while (enumerator.MoveNext()) { VRageMath.Vector3 dir = enumerator.Current; VRageMath.Vector3 gridDir = VRageMath.Vector3.Transform(dir, fromReference); float lengthToMax = (diffMax * gridDir).Max(); float lengthToMin = (diffMin * gridDir).Max(); float offset = Sensors.getOffset(VRageMath.Vector3.Transform(gridDir, toSensor)); float value = _astroidDetectSize + (Math.Max(lengthToMax, lengthToMin) + offset) * gridSize; value = Math.Max(Math.Min(value, sensors.Max), sensors.Min); sensors.Extend(dir, id, value); } }
/// <summary> /// Calculates a transformation matrix to transform grid coordinates to world coordinates. /// </summary> /// <param name="blocks"></param> /// <returns></returns> public static VRageMath.Matrix toWorld(List <IMyCubeBlock> blocks) { if (blocks == null) { throw new Exception("The block list is null"); } if (blocks.Count < 3) { throw new Exception("Need at least 3 blocks."); } IMyCubeBlock origin = blocks[0]; VRageMath.Vector3 localCoord = origin.Position; // first basis vector VRageMath.Vector3 u = blocks[1].Position - localCoord; // second basis vector int vIndex = 2; VRageMath.Vector3 v = blocks[vIndex].Position - localCoord; while (u.Dot(v) * u.Dot(v) == u.LengthSquared() * v.LengthSquared() && vIndex < blocks.Count) { v = blocks[++vIndex].Position - localCoord; } if (u.Dot(v) * u.Dot(v) == u.LengthSquared() + v.LengthSquared()) { throw new Exception("All blocks are linear dependent => It's not possible to calculate a transformation matrix."); } debug.Append("choose: ").Append(u).Append(v).AppendLine(); VRageMath.Matrix localBasis = VRageMath.Matrix.CreateWorld(localCoord, u, v); VRageMath.Vector3 worldCoord = origin.GetPosition(); // world basis depending on the local bases (same coordinates) VRageMath.Vector3 ug = blocks[1].GetPosition() - worldCoord; VRageMath.Vector3 vg = blocks[vIndex].GetPosition() - worldCoord; VRageMath.Matrix worldBasis = VRageMath.Matrix.CreateWorld(worldCoord, ug, vg); VRageMath.Matrix inverseLocalBasis; // if local basis is orthogonal, take the transposed matrix, because then // the transposed and the inverse matrix are the same and it's obviously // easier to get the transposed matrix. if (VRageMath.Vector3.ArePerpendicular(ref u, ref v)) { inverseLocalBasis = VRageMath.Matrix.Transpose(localBasis); } else { inverseLocalBasis = VRageMath.Matrix.Invert(localBasis); } return(inverseLocalBasis * worldBasis); }
public void FromMatrix(ref VRageMath.Matrix matrix) { Quaternion quaternion; this.Position = matrix.Translation; Quaternion.CreateFromRotationMatrix(ref matrix, out quaternion); this.Orientation = new HalfVector4(quaternion.ToVector4()); }
/// <summary> /// Calculates a transformation matrix to transform grid coordinates to world coordinates. /// </summary> /// <param name="blocks"></param> /// <returns></returns> public static VRageMath.Matrix ToWorld(List <IMyCubeBlock> blocks) { if (blocks == null) { throw new Exception("The block list is null"); } if (blocks.Count < 3) { throw new Exception("Need at least 3 blocks."); } IMyCubeBlock origin = blocks[0]; VRageMath.Vector3 localCoord = origin.Position; // first basis vector VRageMath.Vector3 u = blocks[1].Position - localCoord; // second basis vector int vIndex = 2; VRageMath.Vector3 v = blocks[vIndex].Position - localCoord; // TODO use an epsilon value instead of 0, because of the precision error of floating point multiplication. while (u.Dot(v) == 0 && vIndex < blocks.Count) { v = blocks[++vIndex].Position - localCoord; } if (u.Dot(v) == 0) { throw new Exception("All blocks are linear dependent => It's not possible to calculate a transformation matrix."); } VRageMath.Matrix localBasis = VRageMath.Matrix.CreateWorld(localCoord, u, v); VRageMath.Vector3 worldCoord = origin.GetPosition(); // world basis depending on the local bases (same coordinates) VRageMath.Vector3 ug = blocks[1].GetPosition() - worldCoord; VRageMath.Vector3 vg = blocks[vIndex].GetPosition() - worldCoord; VRageMath.Matrix worldBasis = VRageMath.Matrix.CreateWorld(worldCoord, ug, vg); VRageMath.Matrix inverseLocalBasis; // if local basis is orthogonal, take the transposed matrix, because then // the transposed and the inverse matrix are the same and it's obviously // easier to get the transposed matrix. if (VRageMath.Vector3.ArePerpendicular(ref u, ref v)) { inverseLocalBasis = VRageMath.Matrix.Transpose(localBasis); } else { inverseLocalBasis = VRageMath.Matrix.Invert(localBasis); } return(inverseLocalBasis * worldBasis); }
// this is tricky call. The method assumes that Draw() has been called in this frame public void DrawGlass(MyRenderContext RC) { RC.SetPrimitiveTopology(PrimitiveTopology.TriangleList); RC.SetViewport(m_viewport.OffsetX, m_viewport.OffsetY, m_viewport.Width, m_viewport.Height); //RC.SetRtvs(m_gbuffer, MyDepthStencilAccess.ReadWrite); <- the rtv is set out of the pass... FillConstantBuffer(RC, MyCommon.ProjectionConstants, Matrix.Transpose(m_viewProjMatrix)); RC.VertexShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.VertexShader.SetConstantBuffer(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants); RC.PixelShader.SetSamplers(0, MySamplerStateManager.StandardSamplers); RC.PixelShader.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.PixelShader.SetSrv(MyCommon.DITHER_8X8_SLOT, MyGeneratedTextureManager.Dithering8x8Tex); IConstantBuffer cbObjectData = GetPlaceholderObjectCB(RC, 255); // <- the lod value does not matter in this case RC.VertexShader.SetConstantBuffer(MyCommon.OBJECT_SLOT, cbObjectData); //RC.PixelShader.SetConstantBuffer(MyCommon.OBJECT_SLOT, cbObjectData); foreach (var itGroup in m_drawableGroupFactory.GetRawDrawableGroups()) { MyRenderProxy.Assert(itGroup.InstancesCount != 0); MyRenderProxy.Assert(itGroup.InstancesCount == itGroup.InstancesIncrement); if (itGroup.Lod.GlassParts == null) { continue; } foreach (var part in itGroup.Lod.GlassParts) { MyGlassMaterial material = part.GlassMaterial; RC.SetVertexBuffer(0, part.Parent.VB0); RC.SetVertexBuffer(1, part.Parent.VB1); RC.SetVertexBuffer(2, m_vbInstances); RC.SetIndexBuffer(part.Parent.IB); MyShaderBundle shaderBundle = part.GetShaderBundle(itGroup.State); RC.SetInputLayout(shaderBundle.InputLayout); RC.VertexShader.Set(shaderBundle.VertexShader); RC.PixelShader.Set(shaderBundle.PixelShader); RC.PixelShader.SetSrvs(0, material.Srvs); RC.PixelShader.SetConstantBuffer(MyCommon.OBJECT_SLOT, GetGlassCB(RC, material)); int numInstances = itGroup.InstancesCount; int ibOffset = itGroup.OffsetInInstanceBuffer + (part.InstanceMaterialOffsetInLod + 1) * itGroup.InstancesCount; RC.DrawIndexedInstanced(part.IndicesCount, numInstances, part.StartIndex, part.StartVertex, ibOffset); } } }
internal void AddSphereRing(BoundingSphere sphere, Color color, Matrix onb) { float increment = 1.0f / 32; for (float i = 0; i < 1; i += increment) { float a0 = 2 * (float)Math.PI * i; float a1 = 2 * (float)Math.PI * (i + increment); Add( Vector3.Transform(new Vector3(Math.Cos(a0), 0, Math.Sin(a0)) * sphere.Radius, onb) + sphere.Center, Vector3.Transform(new Vector3(Math.Cos(a1), 0, Math.Sin(a1)) * sphere.Radius, onb) + sphere.Center, color); } }
private void SetMatrix(ref VRageMath.Matrix value) { this.matrix = value; this.planes[2].Normal.X = -value.M14 - value.M11; this.planes[2].Normal.Y = -value.M24 - value.M21; this.planes[2].Normal.Z = -value.M34 - value.M31; this.planes[2].D = -value.M44 - value.M41; this.planes[3].Normal.X = -value.M14 + value.M11; this.planes[3].Normal.Y = -value.M24 + value.M21; this.planes[3].Normal.Z = -value.M34 + value.M31; this.planes[3].D = -value.M44 + value.M41; this.planes[4].Normal.X = -value.M14 + value.M12; this.planes[4].Normal.Y = -value.M24 + value.M22; this.planes[4].Normal.Z = -value.M34 + value.M32; this.planes[4].D = -value.M44 + value.M42; this.planes[5].Normal.X = -value.M14 - value.M12; this.planes[5].Normal.Y = -value.M24 - value.M22; this.planes[5].Normal.Z = -value.M34 - value.M32; this.planes[5].D = -value.M44 - value.M42; this.planes[0].Normal.X = -value.M13; this.planes[0].Normal.Y = -value.M23; this.planes[0].Normal.Z = -value.M33; this.planes[0].D = -value.M43; this.planes[1].Normal.X = -value.M14 + value.M13; this.planes[1].Normal.Y = -value.M24 + value.M23; this.planes[1].Normal.Z = -value.M34 + value.M33; this.planes[1].D = -value.M44 + value.M43; for (int i = 0; i < 6; i++) { float num2 = this.planes[i].Normal.Length(); this.planes[i].Normal = (Vector3)(this.planes[i].Normal / num2); this.planes[i].D /= num2; } Ray ray = ComputeIntersectionLine(ref this.planes[0], ref this.planes[2]); this.cornerArray[0] = ComputeIntersection(ref this.planes[4], ref ray); this.cornerArray[3] = ComputeIntersection(ref this.planes[5], ref ray); Ray ray2 = ComputeIntersectionLine(ref this.planes[3], ref this.planes[0]); this.cornerArray[1] = ComputeIntersection(ref this.planes[4], ref ray2); this.cornerArray[2] = ComputeIntersection(ref this.planes[5], ref ray2); ray2 = ComputeIntersectionLine(ref this.planes[2], ref this.planes[1]); this.cornerArray[4] = ComputeIntersection(ref this.planes[4], ref ray2); this.cornerArray[7] = ComputeIntersection(ref this.planes[5], ref ray2); ray2 = ComputeIntersectionLine(ref this.planes[1], ref this.planes[3]); this.cornerArray[5] = ComputeIntersection(ref this.planes[4], ref ray2); this.cornerArray[6] = ComputeIntersection(ref this.planes[5], ref ray2); }
public void Init(int passId, Matrix viewProjMatrix, MyViewport viewport, IDsvBindable dsv, bool isCascade, string debugName) { m_viewProjMatrix = viewProjMatrix; m_viewport = viewport; m_dsv = dsv; m_isCascade = isCascade; if (isCascade) { Init(passId, debugName, MyFrustumEnum.ShadowCascade, MyPassIdResolver.GetCascadeDepthPassIdx(passId)); } else { Init(passId, debugName, MyFrustumEnum.ShadowProjection, MyPassIdResolver.GetSingleDepthPassIdx(passId)); } }
private void SetupSensors() { if (sensors == null) { throw new Exception("No sensors available (sensors == null)."); } VRageMath.BoundingBox bb = GetBounds(); VRageMath.Matrix fromReference = new VRageMath.Matrix(); ReferenceBlock.Orientation.GetMatrix(out fromReference); //VRageMath.Vector3 v = m.Forward.Min() < 0 ? -m.Forward * bb.Min + (XUtils.One + m.Forward) * bb.Max : (XUtils.One - m.Forward) * bb.Min + m.Forward * bb.Max; _sensorIds.Clear(); // Asteroid search laser int id = sensors.GetClosestSensor(bb.Center, _sensorIds); if (id == sensors.CountSensors) { throw new Exception("Not enough sensors."); } _sensorIds.Add(id); var sensor = sensors[id]; sensors.ExtendFront(id, sensors.Max); sensors.ExtendBack(id, sensors.Min); sensors.ExtendBottom(id, sensors.Min); sensors.ExtendLeft(id, sensors.Min); sensors.ExtendRight(id, sensors.Min); sensors.ExtendTop(id, sensors.Min); Sensors.SetFlags(sensor, Sensors.Action.DetectAsteroids.Value); sensor.GetActionWithName("OnOff_On").Apply(sensor); sensor.RequestShowOnHUD(true); sensor.SetCustomName(sensor.DefinitionDisplayNameText + " X Laser"); // Asteroid collision detector id = sensors.GetClosestSensor(bb.Center, _sensorIds); if (id == sensors.CountSensors) { throw new Exception("Not enough sensors."); } _sensorIds.Add(id); sensor = sensors[id]; SetupDrillSensor(fromReference, id, bb); Sensors.SetFlags(sensor, Sensors.Action.DetectAsteroids.Value); sensor.GetActionWithName("OnOff_On").Apply(sensors[id]); sensor.RequestShowOnHUD(true); sensor.SetCustomName(sensor.DefinitionDisplayNameText + " X Drill"); }
public static void CalculateRotation(ref VRageMath.Vector3 a, ref VRageMath.Vector3 b, out VRageMath.Matrix rotation) { if (!VRageMath.Vector3.IsUnit(ref a)) { a.Normalize(); } if (!VRageMath.Vector3.IsUnit(ref b)) { b.Normalize(); } VRageMath.Vector3 v = a.Cross(b); float s = v.Length(); // sine float c = a.Dot(b); // cosine VRageMath.Matrix cross = Utils.CreateSkewSymmetricMatrix(v); rotation = Identity + cross + cross * cross * (1 - c) / s; }
internal virtual void Cleanup() { m_RC = null; if (Locals != null) { Locals.Clear(); } Stats.Clear(); m_joined = false; m_currentProfilingBlock_renderableType = -1; m_currentProfilingBlock_renderableMaterial = string.Empty; m_isImmediate = false; ViewProjection = default(Matrix); Viewport = default(MyViewport); DebugName = string.Empty; ProcessingMask = 0; }
public void ApplyAction(VRageMath.Vector3 dir, string name) { if (!XUtils.Directions.Contains(dir)) { throw new Exception("Invalid direction vector used: " + dir); } VRageMath.Matrix local = new VRageMath.Matrix(); referenceBlock.Orientation.GetMatrix(out local); dir = VRageMath.Vector3.Transform(dir, local); var list = thrusterBlocks[dir]; for (int i = 0; i < list.Count; ++i) { IMyThrust thruster = list[i]; thruster.GetActionWithName(name).Apply(thruster); } }
public void Main() { var blocks = GridTerminalSystem.Blocks; if (blocks.Count == 0) { throw new Exception("Did not find any block. Not even this one?! WTF?!"); } reference = blocks[0]; perpBlocks = Utils.FindPerpendicularTo(reference); for (int i = 0; i < perpBlocks.Count; ++i) { var block = perpBlocks[i]; debug.Append(block.Position).AppendLine(); } return; bool orthogonal = perpBlocks.Count == 3; VRageMath.Matrix toWorld = orthogonal ? Utils.toWorld(perpBlocks) : Utils.toWorld(GridTerminalSystem.Blocks); var projectors = new List <IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType <IMyProjector>(projectors); if (projectors.Count == 0) { throw new Exception("Did not find any projector."); } var projector = projectors[0]; var resultList = new List <ITerminalProperty>(); projector.GetProperties(resultList); for (int i = 0; i < resultList.Count; ++i) { debug.Append(resultList[i].TypeName).Append(" ").Append(resultList[i].Id).AppendLine(); } }
public static void Draw() { // We can fill vertex buffer only when in Draw LoadInDraw(); //RasterizerState.CullClockwise.Apply(); RasterizerState.CullNone.Apply(); DepthStencilState.None.Apply(); BlendState.Opaque.Apply(); m_backgroundProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MyRenderCamera.FieldOfView, MyRenderCamera.AspectRatio, MyRenderCamera.NEAR_PLANE_DISTANCE, 100000); if (MyRender.CurrentRenderSetup.BackgroundColor != null) { MyRender.GraphicsDevice.Clear(ClearFlags.Target, new SharpDX.ColorBGRA(MyRender.CurrentRenderSetup.BackgroundColor.Value.R, MyRender.CurrentRenderSetup.BackgroundColor.Value.G, MyRender.CurrentRenderSetup.BackgroundColor.Value.B, MyRender.CurrentRenderSetup.BackgroundColor.Value.A), 1, 0); } else if (m_textureCube != null) { MyEffectBackgroundCube effect = MyRender.GetEffect(MyEffects.BackgroundCube) as MyEffectBackgroundCube; effect.SetViewProjectionMatrix(MyRenderCamera.ViewMatrixAtZero * m_backgroundProjectionMatrix); effect.SetBackgroundTexture(m_textureCube); effect.SetBackgroundColor(BackgroundColor); MyRender.GraphicsDevice.VertexDeclaration = MyVertexFormatPositionTexture3.VertexDeclaration; MyRender.GraphicsDevice.SetStreamSource(0, m_boxVertexBuffer, 0, MyVertexFormatPositionTexture3.Stride); effect.Begin(); MyRender.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, BOX_TRIANGLES_COUNT); effect.End(); MyPerformanceCounter.PerCameraDrawWrite.TotalDrawCalls++; } else { MyRender.GraphicsDevice.Clear(ClearFlags.Target, new SharpDX.ColorBGRA(BackgroundColor.X, BackgroundColor.Y, BackgroundColor.Z, 1), 1, 0); } }
public override void LoadContent() { MyRender.Log.WriteLine("MyBackgroundCube.LoadContent() - START"); MyRender.Log.IncreaseIndent(); MyRender.GetRenderProfiler().StartProfilingBlock("MyBackgroundCube"); Static = this; UpdateTexture(); m_loaded = false; // Projection matrix according to zoom level m_backgroundProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(1.0f, MyRenderCamera.AspectRatio, 50, 100000); MyRender.GetRenderProfiler().EndProfilingBlock(); MyRender.Log.DecreaseIndent(); MyRender.Log.WriteLine("MyBackgroundCube.LoadContent() - END"); }
public void UpdateBlocks(List <IMyTerminalBlock> list) { gyros = new List <IMyGyro>(); thrusters = new Dictionary <VRageMath.Vector3, List <IMyThrust> >(); VRageMath.Matrix tmp = new VRageMath.Matrix(); for (int i = 0; i < list.Count; ++i) { var block = list[i]; if (block is IMyGyro) { IMyGyro gyro = (IMyGyro)block; if (gyros.Count == 0) { gyroRotateMin = gyro.GetMininum <float>(GyroAction.Pitch.GetName()); gyroRotateMax = gyro.GetMaximum <float>(GyroAction.Pitch.GetName()); } gyros.Add(gyro); } else if (block is IMyThrust) { IMyThrust thruster = block as IMyThrust; if (thrusters.Count == 0) { thrusterOverrideMin = thruster.GetMininum <float>("Override"); thrusterOverrideMax = thruster.GetMaximum <float>("Override"); } block.Orientation.GetMatrix(out tmp); // The exhaust is directed to the Forward vector of the thruster, so it accelerates to Backward. VRageMath.Vector3 dir = tmp.Backward; if (!thrusters.ContainsKey(dir)) { thrusters[dir] = new List <IMyThrust>(); } thrusters[dir].Add(thruster); } } }
internal virtual void Begin() { MyUtils.Init(ref Locals); Locals.Clear(); //if (!m_isImmediate) //{ // //Debug.Assert(m_RC == null); // //m_RC = MyRenderContextPool.AcquireRC(); //} var viewProjTranspose = Matrix.Transpose(ViewProjection); var mapping = MyMapping.MapDiscard(RC, MyCommon.ProjectionConstants); mapping.WriteAndPosition(ref viewProjTranspose); mapping.Unmap(); // common settings RC.SetPrimitiveTopology(PrimitiveTopology.TriangleList); RC.SetViewport(Viewport.OffsetX, Viewport.OffsetY, Viewport.Width, Viewport.Height); RC.PixelShader.SetSamplers(0, MySamplerStateManager.StandardSamplers); RC.AllShaderStages.SetConstantBuffer(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.AllShaderStages.SetConstantBuffer(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants); RC.AllShaderStages.SetConstantBuffer(MyCommon.VOXELS_MATERIALS_LUT_SLOT, MyCommon.VoxelMaterialsConstants.Cb); RC.AllShaderStages.SetConstantBuffer(MyCommon.ALPHAMASK_VIEWS_SLOT, MyCommon.AlphamaskViewsConstants); RC.PixelShader.SetSrv(MyCommon.DITHER_8X8_SLOT, MyGeneratedTextureManager.Dithering8x8Tex); if (MyBigMeshTable.Table.m_IB != null) { var slotcounter = MyCommon.BIG_TABLE_INDICES; RC.VertexShader.SetSrv(slotcounter++, MyBigMeshTable.Table.m_IB); RC.VertexShader.SetSrv(slotcounter++, MyBigMeshTable.Table.m_VB_positions); RC.VertexShader.SetSrv(slotcounter++, MyBigMeshTable.Table.m_VB_rest); } }
internal void AddCone(Vector3 translation, Vector3 directionVec, Vector3 baseVec, int tessalation, Color color) { var axis = directionVec; axis.Normalize(); var apex = translation + directionVec; var steps = tessalation; var stepsRcp = (float)(Math.PI * 2 / steps); for (int i = 0; i < 32; i++) { float a0 = i * stepsRcp; float a1 = (i + 1) * stepsRcp; var A = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a0)); var B = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a1)); Add(A, B, color); Add(A, apex, color); } }
/// <summary> /// Rotates the ship relative to the reference block. /// A positive Yaw value rotates around the Up vector, such that the Right vector is moved to the Backward vector on the shortest way. /// A positive Pitch value rotates around the Right vector, such that the Up vector is moved to the Backward vector on the shortest way. /// A positive Roll value rotates around the Backward vector, such that the Up vector is moved to the Right vector on the shortest way. /// </summary> /// <param name="axis"></param> /// <param name="value"></param> private void Rotate(VRageMath.Vector3 axis, float value) { if (value < Min || value > Max) { throw new Exception("Value '" + value + "' out of range [" + Min + ", " + Max + "]."); } VRageMath.Matrix local = new VRageMath.Matrix(); referenceBlock.Orientation.GetMatrix(out local); axis = VRageMath.Vector3.Transform(axis, local); for (int i = 0; i < gyroscopeBlocks.Count; ++i) { IMyGyro gyro = gyroscopeBlocks[i] as IMyGyro; gyro.Orientation.GetMatrix(out local); VRageMath.Matrix toGyro = VRageMath.Matrix.Transpose(local); VRageMath.Vector3 transformedAxis = VRageMath.Vector3.Transform(axis, toGyro); GyroAction action = GyroAction.getActionAroundAxis(transformedAxis); gyro.SetValue(action.Name, action.Reversed ? -value : value); } }
/// <summary> /// Rotates the ship relative to the reference block. /// A positive Yaw value rotates around the Up vector, such that the Right vector is moved to the Backward vector on the shortest way. /// A positive Pitch value rotates around the Right vector, such that the Up vector is moved to the Backward vector on the shortest way. /// A positive Roll value rotates around the Backward vector, such that the Up vector is moved to the Right vector on the shortest way. /// </summary> /// <param name="axis"></param> /// <param name="value"></param> public void Rotate(VRageMath.Vector3 axis, float value) { if (value < gyroRotateMin || value > gyroRotateMax) { throw new Exception("Value out of range [" + gyroRotateMin + ", " + gyroRotateMax + "]."); } VRageMath.Matrix local = new VRageMath.Matrix(); referenceBlock.Orientation.GetMatrix(out local); axis = VRageMath.Vector3.Transform(axis, local); for (int i = 0; i < gyros.Count; ++i) { IMyGyro gyro = gyros[i] as IMyGyro; gyro.Orientation.GetMatrix(out local); VRageMath.Matrix toGyro = VRageMath.Matrix.Transpose(local); VRageMath.Vector3 transformedAxis = VRageMath.Vector3.Transform(axis, toGyro); GyroAction action = gyroActions[transformedAxis]; gyro.SetValue(action.GetName(), action.Reversed ? -value : value); } }
void InitRenderPasses(MyCullQuery cullQuery, List <MyRenderPass> renderPasses) { renderPasses.Clear(); foreach (var query in cullQuery.RenderingPasses) { if (query == null) { continue; } Matrix matrix = query.ViewProjection; MyViewport viewport = query.Viewport; if (query is VRageRender.MyGBufferPass) { VRageRender.MyGBufferPass oldGBufferPass = (VRageRender.MyGBufferPass)query; MyGBuffer gbuffer = oldGBufferPass.GBuffer; MyGBufferPass gbufferPass; int passId = GetPassId(oldGBufferPass); m_gbufferPassesPool.AllocateOrCreate(out gbufferPass); gbufferPass.Init(passId, matrix, viewport, gbuffer); renderPasses.Add(gbufferPass); } if (query is VRageRender.MyDepthPass) { VRageRender.MyDepthPass oldDepthPass = (VRageRender.MyDepthPass)query; IDsvBindable dsv = oldDepthPass.Dsv; MyDepthPass depthPass; bool isCascade = oldDepthPass.IsCascade; int passId = GetPassId(oldDepthPass); m_depthPassesPool.AllocateOrCreate(out depthPass); depthPass.Init(passId, matrix, viewport, dsv, isCascade, oldDepthPass.DebugName); renderPasses.Add(depthPass); } } }
internal virtual void Begin() { MyUtils.Init(ref Locals); Locals.Clear(); //if (!m_isImmediate) //{ // //Debug.Assert(m_RC == null); // //m_RC = MyRenderContextPool.AcquireRC(); //} var viewProjTranspose = Matrix.Transpose(ViewProjection); var mapping = MyMapping.MapDiscard(RC.DeviceContext, MyCommon.ProjectionConstants); mapping.WriteAndPosition(ref viewProjTranspose); mapping.Unmap(); // common settings Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; Context.Rasterizer.SetViewport(Viewport.OffsetX, Viewport.OffsetY, Viewport.Width, Viewport.Height); Context.PixelShader.SetSamplers(0, MyRender11.StandardSamplers); RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.SetCB(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants); RC.SetCB(MyCommon.ALPHAMASK_VIEWS_SLOT, MyCommon.AlphamaskViewsConstants); Context.PixelShader.SetShaderResource(MyCommon.DITHER_8X8_SLOT, MyTextures.Views[MyTextures.Dithering8x8TexId.Index]); if (MyBigMeshTable.Table.m_IB != null) { var slotcounter = MyCommon.BIG_TABLE_INDICES; RC.VSBindSRV(slotcounter++, MyBigMeshTable.Table.m_IB.Srv); RC.VSBindSRV(slotcounter++, MyBigMeshTable.Table.m_VB_positions.Srv); RC.VSBindSRV(slotcounter++, MyBigMeshTable.Table.m_VB_rest.Srv); } }
/// <summary> /// Accelerates the ship relative to the reference block. /// </summary> /// <param name="dir">The direction relative to the reference block in which the ship should be accelerated.</param> /// <param name="value">The amount of force to accelerate in Newton.</param> public void Accelerate(VRageMath.Vector3 dir, float value) { if (value < thrusterOverrideMin || value > thrusterOverrideMax) { throw new Exception("Value out of range [" + thrusterOverrideMin + ", " + thrusterOverrideMax + "]."); } VRageMath.Matrix local = new VRageMath.Matrix(); referenceBlock.Orientation.GetMatrix(out local); dir = VRageMath.Vector3.Transform(dir, local); if (!thrusters.ContainsKey(dir)) { throw new Exception("Warning! No thruster in direction " + dir + "."); } var list = thrusters[dir]; for (int i = 0; i < list.Count; ++i) { IMyThrust thruster = list[i]; thruster.SetValueFloat("Override", value); } }
internal void SetCustomViewProjection(ref Matrix m) { m_customViewProjection = m; }
void IMyEntity.SetLocalMatrix(VRageMath.Matrix localMatrix, object source) { PositionComp.SetLocalMatrix(localMatrix, source); }
void Main() { // initialize var blocks = new List <IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType <IMyShipController>(blocks, FilterShipController); if (blocks.Count == 0) { throw new Exception("Did not find any cockpit."); } controller = blocks[0] as IMyShipController; debug.Append("use ").Append(controller.CustomName).Append(':').AppendLine(); perpBlocks = Utils.FindPerpendicularTo(controller); for (int i = 0; i < perpBlocks.Count; ++i) { var block = perpBlocks[i]; debug.Append(block.Position).AppendLine(); } VRageMath.Vector3 cur = perpBlocks[1].Position - perpBlocks[0].Position; VRageMath.Vector3 next = perpBlocks[2].Position - perpBlocks[0].Position; debug.Append(VRageMath.Vector3.ArePerpendicular(ref cur, ref next)).AppendLine(); worldCoord = new VRageMath.Vector3D(0, 0, 0); bool orthogonal = perpBlocks.Count == 3; VRageMath.Matrix toWorld = orthogonal ? Utils.toWorld(perpBlocks) : Utils.toWorld(GridTerminalSystem.Blocks); VRageMath.Vector3 r = toWorld.Right; VRageMath.Vector3 u = toWorld.Up; VRageMath.Vector3 b = toWorld.Backward; debug.Append(r.Dot(u)).AppendLine(); debug.Append(u.Dot(b)).AppendLine(); debug.Append(b.Dot(r)).AppendLine(); debug.Append(VRageMath.Vector3.ArePerpendicular(ref r, ref u)).AppendLine(); debug.Append(VRageMath.Vector3.ArePerpendicular(ref u, ref b)).AppendLine(); debug.Append(VRageMath.Vector3.ArePerpendicular(ref b, ref r)).AppendLine(); blocks = new List <IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType <IMyThrust>(blocks); GridTerminalSystem.GetBlocksOfType <IMyGyro>(blocks); debug.Append("worldCoord = ").Append(VRageMath.Vector3I.Round(worldCoord)).AppendLine(); debug.Append("controller.GetPosition() = ").Append(VRageMath.Vector3I.Round(controller.GetPosition())).AppendLine(); debug.Append("controller.Position = ").Append(controller.Position).AppendLine(); debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.Position, toWorld))).AppendLine(); debug.Append("transfrom controller.GetPosition() = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.GetPosition(), VRageMath.Matrix.Invert(toWorld)))).AppendLine(); debug.Append("transfrom zero = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(worldCoord, VRageMath.Matrix.Invert(toWorld)))).AppendLine(); VRageMath.Vector3 worldDir = worldCoord - controller.GetPosition(); float distance = worldDir.LengthSquared() > 0 ? worldDir.Normalize() : 0; debug.Append("distance = ").Append(distance).AppendLine(); debug.Append("direction = ").Append(worldDir).AppendLine(); VRageMath.Matrix worldController = new VRageMath.Matrix(); controller.Orientation.GetMatrix(out worldController); worldController = worldController * VRageMath.Matrix.CreateTranslation(controller.Position) * toWorld; debug.Append("worldController = ").AppendLine(); debug.Append(worldController.Right).AppendLine(); debug.Append(worldController.Up).AppendLine(); debug.Append(worldController.Backward).AppendLine(); debug.Append(worldController.Translation).AppendLine(); VRageMath.Vector3 a = worldController.Forward; VRageMath.Matrix rotation = Utils.CalculateRotation(ref worldDir, ref a); debug.Append((double)Math.Abs(rotation.Right.Dot(rotation.Up))).AppendLine(); debug.Append((double)Math.Abs(rotation.Right.Dot(rotation.Backward))).AppendLine(); debug.Append((double)Math.Abs(rotation.Up.Dot(rotation.Backward))).AppendLine(); debug.Append("rotation transl+persp = ").Append(rotation.HasNoTranslationOrPerspective()).AppendLine(); debug.Append("rotation rotation = ").Append(rotation.IsRotation()).AppendLine(); debug.Append(rotation.Right).AppendLine(); debug.Append(rotation.Up).AppendLine(); debug.Append(rotation.Backward).AppendLine(); debug.Append(rotation.Translation).AppendLine(); VRageMath.Vector3 xyz = new VRageMath.Vector3(); VRageMath.Matrix.GetEulerAnglesXYZ(ref rotation, out xyz); debug.Append("X = ").Append(xyz.GetDim(0)).AppendLine(); debug.Append("Y = ").Append(xyz.GetDim(1)).AppendLine(); debug.Append("Z = ").Append(xyz.GetDim(2)).AppendLine(); Debug(debug.ToString()); debug.Clear(); }
internal void AddSphereRing(BoundingSphere sphere, Color color, Matrix onb) { float increment = 1.0f / 32; for (float i=0; i < 1; i += increment) { float a0 = 2* (float)Math.PI * i; float a1 = 2* (float)Math.PI * (i + increment); Add( Vector3.Transform(new Vector3(Math.Cos(a0), 0, Math.Sin(a0)) * sphere.Radius, onb) + sphere.Center, Vector3.Transform(new Vector3(Math.Cos(a1), 0, Math.Sin(a1)) * sphere.Radius, onb) + sphere.Center, color); } }
void Main() { // initialize var blocks = new List <IMyTerminalBlock>(); if (counter == 0) { GridTerminalSystem.GetBlocksOfType <IMyShipController>(blocks, FilterShipController); if (blocks.Count == 0) { throw new Exception("Did not find any cockpit."); } controller = blocks[0] as IMyShipController; debug.Append("use ").Append(controller.CustomName).Append(':').AppendLine(); perpBlocks = Utils.FindPerpendicularTo(controller); ship = new ShipController(controller); worldCoord = controller.GetPosition(); debug.Append("POSITION = ").Append(worldCoord).AppendLine(); Debug(debug.ToString()); debug.Clear(); counter++; return; } worldCoord = new VRageMath.Vector3D(0, 0, 0); bool orthogonal = perpBlocks.Count == 3; VRageMath.Matrix toWorld = orthogonal ? Utils.toWorld(GridTerminalSystem.Blocks) : Utils.toWorld(perpBlocks); blocks = new List <IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType <IMyThrust>(blocks); GridTerminalSystem.GetBlocksOfType <IMyGyro>(blocks); debug.Append("worldCoord = ").Append(VRageMath.Vector3I.Round(worldCoord)).AppendLine(); debug.Append("controller.GetPosition() = ").Append(VRageMath.Vector3I.Round(controller.GetPosition())).AppendLine(); debug.Append("controller.Position = ").Append(controller.Position).AppendLine(); debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.Position, toWorld))).AppendLine(); debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.GetPosition(), VRageMath.Matrix.Invert(toWorld)))).AppendLine(); VRageMath.Vector3 worldDir = worldCoord - controller.GetPosition(); float distance = worldDir.LengthSquared() > 0 ? worldDir.Normalize() : 0; debug.Append("distance = ").Append(distance).AppendLine(); debug.Append("direction = ").Append(worldDir).AppendLine(); VRageMath.Matrix worldController = new VRageMath.Matrix(); controller.Orientation.GetMatrix(out worldController); worldController = worldController * toWorld; debug.Append("worldController = ").AppendLine(); debug.Append(worldController.Right).AppendLine(); debug.Append(worldController.Up).AppendLine(); debug.Append(worldController.Backward).AppendLine(); debug.Append(worldController.Translation).AppendLine(); debug.Append("origin worldController = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(new VRageMath.Vector3(), worldController))).AppendLine(); //VRageMath.Vector3 n = orthogonal ? worldController.Right : worldController.Up.Cross(worldController.Backward); //VRageMath.Vector3 projDir = worldDir - worldDir.Dot(n) / n.Dot(n) * n; //if (projDir.LengthSquared() > 0) // projDir.Normalize(); //VRageMath.Vector3 eY = worldController.Up; //eY.Normalize(); //VRageMath.Vector3 eZ = worldController.Backward; //eZ.Normalize(); //float cosinePhiY = eY.Dot(projDir); //float cosinePhiZ = eZ.Dot(projDir); //float pitch = (float)(cosinePhiY > 0 ? -Math.Acos(cosinePhiZ) : Math.Acos(cosinePhiZ)); ////VRageMath.Matrix.AlignRotationToAxes(); //debug.Append("pitch = ").Append(pitch).AppendLine(); debug.Append("worldController.IsRotation() = ").Append(worldController.IsRotation()); VRageMath.Matrix toAlign = VRageMath.Matrix.CreateFromDir(worldDir, worldController.Up); VRageMath.Matrix align = VRageMath.Matrix.AlignRotationToAxes(ref toAlign, ref worldController); VRageMath.Vector3 xyz = new VRageMath.Vector3(); VRageMath.Matrix.GetEulerAnglesXYZ(ref align, out xyz); xyz = 0.1f * xyz; debug.Append(xyz).AppendLine(); ship.UpdateBlocks(blocks); ship.Stop(); ship.Rotate(Identity.Left, xyz.GetDim(0)); ship.Rotate(Identity.Down, xyz.GetDim(1)); ship.Rotate(Identity.Forward, xyz.GetDim(2)); Debug(debug.ToString()); debug.Clear(); }
internal virtual void Cleanup() { m_RC = null; if(Locals != null) Locals.Clear(); Stats.Clear(); m_joined = false; m_currentProfilingBlock_renderableType = -1; m_currentProfilingBlock_renderableMaterial = string.Empty; m_isImmediate = false; ViewProjection = default(Matrix); Viewport = default(MyViewport); DebugName = string.Empty; ProcessingMask = 0; }
internal unsafe override sealed void RecordCommands(MyRenderableProxy proxy) { if (proxy.Mesh.Buffers.IB == IndexBufferId.NULL || proxy.DrawSubmesh.IndexCount == 0 || proxy.SkipIfTooSmall()) { return; } Stats.Meshes++; SetProxyConstants(proxy); BindProxyGeometry(proxy); Debug.Assert(proxy.DepthShaders.VS != null); RC.BindShaders(proxy.DepthShaders); if ((proxy.Flags & MyRenderableProxyFlags.DisableFaceCulling) > 0) { RC.SetRS(MyRender11.m_nocullRasterizerState); } else { RC.SetRS(DefaultRasterizer); } //for (int i = 0; i < proxy.depthOnlySubmeshes.Length; i++) //{ // Stats.Submeshes++; // var submesh = proxy.depthOnlySubmeshes[i]; var submesh = proxy.DrawSubmesh; if (submesh.MaterialId != Locals.matTexturesID && (!((proxy.Flags & MyRenderableProxyFlags.DepthSkipTextures) > 0))) { Stats.MaterialConstantsChanges++; Locals.matTexturesID = submesh.MaterialId; var material = MyMaterials1.ProxyPool.Data[submesh.MaterialId.Index]; RC.MoveConstants(ref material.MaterialConstants); RC.SetConstants(ref material.MaterialConstants, MyCommon.MATERIAL_SLOT); RC.SetSRVs(ref material.MaterialSRVs); } if (proxy.SkinningMatrices != null) { Stats.ObjectConstantsChanges++; MyObjectData objectData = proxy.ObjectData; //objectData.Translate(-MyEnvironment.CameraPosition); MyMapping mapping; mapping = MyMapping.MapDiscard(RC.Context, proxy.ObjectBuffer); void *ptr = &objectData; mapping.stream.Write(new IntPtr(ptr), 0, sizeof(MyObjectData)); if (proxy.SkinningMatrices != null) { if (submesh.BonesMapping == null) { for (int j = 0; j < Math.Min(MyRender11Constants.SHADER_MAX_BONES, proxy.SkinningMatrices.Length); j++) { mapping.stream.Write(Matrix.Transpose(proxy.SkinningMatrices[j])); } } else { for (int j = 0; j < submesh.BonesMapping.Length; j++) { mapping.stream.Write(Matrix.Transpose(proxy.SkinningMatrices[submesh.BonesMapping[j]])); } } } mapping.Unmap(); } if (proxy.InstanceCount == 0) { RC.Context.DrawIndexed(submesh.IndexCount, submesh.StartIndex, submesh.BaseVertex); RC.Stats.DrawIndexed++; Stats.Instances++; Stats.Triangles += submesh.IndexCount / 3; } else { RC.Context.DrawIndexedInstanced(submesh.IndexCount, proxy.InstanceCount, submesh.StartIndex, submesh.BaseVertex, proxy.StartInstance); RC.Stats.DrawIndexedInstanced++; Stats.Instances += proxy.InstanceCount; Stats.Triangles += proxy.InstanceCount * submesh.IndexCount / 3; } //} }