private void Scene_GetRenderSceneData(Component_Scene scene, ViewportRenderingContext context) { if (DisplayPath) { pathController?.DrawPath(context); } }
void UpdateAttachedScene() { bool needSceneCreate = false; if (createdViewport != null) { Component_Scene scene = null; if (DisplayScene) { scene = Scene.ReferenceSpecified ? Scene.Value : ParentScene; } if (scene != null) { var ins = ComponentUtility.GetResourceInstanceByComponent(scene); var isResource = ins != null && ins.InstanceType == Resource.InstanceType.Resource; if (isResource) { SceneRecreateIfNeeded(scene); scene = createdScene; needSceneCreate = true; } } createdViewport.AttachedScene = scene; } if (!needSceneCreate) { SceneDestroy(); } }
///////////////////////////////////////// public Component_Scene CreateScene(bool enable) { DetachAndOrDestroyScene(); scene = ComponentUtility.CreateComponent <Component_Scene>(null, true, enable); //!!!!что еще отключать? scene.OctreeEnabled = false; //rendering pipeline { var pipeline = (Component_RenderingPipeline)scene.CreateComponent(RenderingSystem.RenderingPipelineDefault, -1, false); scene.RenderingPipeline = pipeline; //!!!!что еще отключать? pipeline.DeferredShading = AutoTrueFalse.False; pipeline.LODRange = new RangeI(0, 0); //pipeline.UseRenderTargets = false; //!!!! scene.BackgroundColor = new ColorValue(0.5, 0.5, 0.5); //scene.BackgroundColor = new ColorValue( 0, 0, 0, 0 ); scene.BackgroundColorAffectLighting = 1; scene.BackgroundColorEnvironmentOverride = new ColorValue(0.8, 0.8, 0.8); pipeline.Enabled = true; } //ambient light { var light = scene.CreateComponent <Component_Light>(); light.Type = Component_Light.TypeEnum.Ambient; light.Brightness = ReferenceUtility.MakeReference("Base\\ProjectSettings.component|PreviewAmbientLightBrightness"); //light.Brightness = ProjectSettings.Get.PreviewAmbientLightBrightness.Value; } //directional light { var light = scene.CreateComponent <Component_Light>(); light.Type = Component_Light.TypeEnum.Directional; light.Transform = new Transform(new Vector3(0, 0, 0), Quaternion.FromDirectionZAxisUp(new Vector3(0, 0, -1)), Vector3.One); light.Brightness = ReferenceUtility.MakeReference("Base\\ProjectSettings.component|PreviewDirectionalLightBrightness"); //light.Brightness = ProjectSettings.Get.PreviewDirectionalLightBrightness.Value; //!!!!? light.Shadows = false; //light.Type = Component_Light.TypeEnum.Point; //light.Transform = new Transform( new Vec3( 0, 0, 2 ), Quat.Identity, Vec3.One ); } scene.ViewportUpdateGetCameraSettings += Scene_ViewportUpdateGetCameraSettings; //connect scene to viewport if (viewport != null) { viewport.AttachedScene = scene; } return(scene); }
private void ParentScene_ViewportUpdateBefore(Component_Scene scene, Viewport viewport, Viewport.CameraSettingsClass overrideCameraSettings) { if (EnabledInHierarchyAndIsNotResource && AutoUpdate && (viewport.LastUpdateTime == lastVisibleTime || viewport.PreviousUpdateTime == lastVisibleTime)) { RenderTargetUpdate(); } }
public static void DestroyPreviewObjects(Component_Scene scene) { foreach (var c in scene.GetComponents <Component_MeshInSpace>()) { c.Dispose(); } }
public static void SetListener(Component_Scene currentScene, Vector3 position, Vector3 velocity, Quaternion rotation) { bool newScene = !ReferenceEquals(listenerCurrentScene, currentScene); double saveVolume = 0; if (newScene) { listenerCurrentScene = currentScene; saveVolume = MasterChannelGroup.Volume; MasterChannelGroup.Volume = 0; } if (listenerPosition != position || listenerVelocity != velocity || listenerRotation != rotation) { listenerPosition = position; listenerVelocity = velocity; listenerRotation = rotation; instance.OnSetListener(listenerPosition, listenerVelocity, listenerRotation); } if (newScene) { MasterChannelGroup.Volume = saveVolume; _Update(true); } }
void SceneRecreateIfNeeded( Component_Scene source ) { if( source != null ) { if( createdSceneSource != source ) SceneCreate( source ); } else SceneDestroy(); }
public void DetachAndOrDestroyScene() { if (scene != null) { if (viewport != null) { viewport.AttachedScene = null; } scene.Dispose(); scene = null; } }
public static void Physics2DRayTest(this Component_Scene scene, Physics2DRayTestItem[] items) { var worldData = Physics2DUtility.GetWorldData(scene, false); if (worldData != null) { //!!!!threading foreach (var item in items) { var result = new List <Physics2DRayTestItem.ResultItem>(); var point1 = Physics2DUtility.Convert(item.Ray.Origin); var point2 = Physics2DUtility.Convert(item.Ray.GetEndPoint()); worldData.world.RayCast((f, p, n, fr) => { if (ShouldCollide(f, item)) { var shape = f.Tag as Component_CollisionShape2D; if (shape != null) { var resultItem = new Physics2DRayTestItem.ResultItem(); resultItem.Body = shape.ParentRigidBody; resultItem.Shape = shape; resultItem.Position = Physics2DUtility.Convert(p); resultItem.Normal = Physics2DUtility.Convert(n); resultItem.DistanceScale = fr; result.Add(resultItem); if (item.Mode == Physics2DRayTestItem.ModeEnum.One) { return(0); } } } return(1); }, point1, point2); RayTest_PostProcess(item, result); } } else { foreach (var item in items) { item.Result = Array.Empty <Physics2DRayTestItem.ResultItem>(); } } }
void SceneDestroy() { if (createdScene != null) { var destroyedScene = createdScene; createdScene.Dispose(); createdScene = null; createdSceneSource = null; SceneDestroyed?.Invoke(this, destroyedScene); } }
// public Physics2DWorldDataImpl(Component_Scene scene) { this.scene = scene; world = new World(); //!!!! //Settings.UseConvexHullPolygons = false; Settings.MaxPolygonVertices = 64; UpdateGravity(); }
void SceneCreate( Component_Scene source ) { SceneDestroy(); var fileName = ComponentUtility.GetOwnedFileNameOfComponent( source ); if( !string.IsNullOrEmpty( fileName ) && VirtualFile.Exists( fileName ) ) createdScene = ResourceManager.LoadSeparateInstance<Component>( fileName, true, null ) as Component_Scene; if( createdScene != null ) SceneCreated?.Invoke( this ); createdSceneSource = source; }
internal void SoundPlayInit(Component_Scene attachedToScene, Sound sound, SoundChannelGroup group) { this.attachedToScene = attachedToScene; this.sound = sound; this.group = group; //!!!!было //sound.playingCount++; //if( ( sound.Mode & SoundModes.Stream ) != 0 ) //{ // if( sound.playingCount != 1 ) // Log.Fatal( "VirtualChannel: SoundPlayInit: sound.playingCount != 1." ); //} }
private void Scene_GetRenderSceneData(Component_Scene scene, ViewportRenderingContext context) { var context2 = context.objectInSpaceRenderingContext; bool display = false; ColorValue color = Color; if (VisibleInHierarchy) { if ((ParentScene.GetDisplayDevelopmentDataInThisApplication() /*&& ParentScene.DisplayLights */) || context2.selectedObjects.Contains(this) || context2.canSelectObjects.Contains(this) || context2.objectToCreate == this) { if (context2.selectedObjects.Contains(this) || context2.canSelectObjects.Contains(this)) { display = true; if (context2.selectedObjects.Contains(this)) { color = ProjectSettings.Get.SelectedColor; } else { color = ProjectSettings.Get.CanSelectColor; } } if (EngineApp.ApplicationType == EngineApp.ApplicationTypeEnum.Editor && DisplayCurveInEditor) { display = true; } } if (EngineApp.ApplicationType == EngineApp.ApplicationTypeEnum.Simulation && DisplayCurveInSimulation) { display = true; } } if (display) { Render(context2, color); } if (!ParentScene.GetDisplayDevelopmentDataInThisApplication()) { context2.disableShowingLabelForThisObject = true; } }
///////////////////////////////////////// static Component_Scene.IPhysics2DWorldData GetPhysics2DWorldDataInit(Component_Scene scene) { return(new Physics2DWorldDataImpl(scene)); }
public static void CreatePreviewObjects(Component_Scene scene, Component_Surface surface) { DestroyPreviewObjects(scene); var center = Vector3.Zero; //!!!!среднее от всех групп double minDistanceBetweenObjects; { var groups = surface.GetComponents <Component_SurfaceGroupOfElements>(); if (groups.Length != 0) { minDistanceBetweenObjects = 0; foreach (var group in groups) { minDistanceBetweenObjects += group.MinDistanceBetweenObjects; } minDistanceBetweenObjects /= groups.Length; } else { minDistanceBetweenObjects = 1; } } //!!!! var toolRadius = minDistanceBetweenObjects * 5; // CreateObjectsBrushRadius; var toolStrength = 1.0; // CreateObjectsBrushStrength; var toolHardness = 0; // CreateObjectsBrushHardness; var random = new Random(0); double GetHardnessFactor(double length) { if (length == 0 || length <= toolHardness * toolRadius) { return(1); } else { double c; if (toolRadius - toolRadius * toolHardness != 0) { c = (length - toolRadius * toolHardness) / (toolRadius - toolRadius * toolHardness); } else { c = 0; } return((float)Math.Cos(Math.PI / 2 * c)); } } //calculate object count int count; { var toolSquare = Math.PI * toolRadius * toolRadius; double radius = minDistanceBetweenObjects / 2; double objectSquare = Math.PI * radius * radius; if (objectSquare < 0.1) { objectSquare = 0.1; } double maxCount = toolSquare / objectSquare; maxCount /= 10; count = (int)(toolStrength * (double)maxCount); count = Math.Max(count, 1); count *= 20; } var data = new List <Component_GroupOfObjects.Object>(count); //create point container to check by MinDistanceBetweenObjects PointContainer3D pointContainerFindFreePlace; { double minDistanceBetweenObjectsMax = 0; foreach (var group in surface.GetComponents <Component_SurfaceGroupOfElements>()) { minDistanceBetweenObjectsMax = Math.Max(minDistanceBetweenObjectsMax, group.MinDistanceBetweenObjects); } var bounds = new Bounds(center); bounds.Expand(toolRadius + minDistanceBetweenObjectsMax); pointContainerFindFreePlace = new PointContainer3D(bounds, 100); } for (int n = 0; n < count; n++) { surface.GetRandomVariation(new Component_Surface.GetRandomVariationOptions(), random, out var groupIndex, out var elementIndex, out var positionZ, out var rotation, out var scale); var surfaceGroup = surface.GetGroup(groupIndex); Vector3?position = null; int counter = 0; while (counter < 20) { var offset = new Vector2(random.Next(toolRadius * 2) - toolRadius, random.Next(toolRadius * 2) - toolRadius); //check by radius and by hardness var length = offset.Length(); if (length <= toolRadius && random.NextDouble() <= GetHardnessFactor(length)) { var position2 = center.ToVector2() + offset; //var result = Component_Scene_Utility.CalculateObjectPositionZ( Scene, toGroupOfObjects, center.Z, position2, destinationCachedBaseObjects ); //if( result.found ) //{ var p = new Vector3(position2, 0); // result.positionZ ); //check by MinDistanceBetweenObjects if (surfaceGroup == null || !pointContainerFindFreePlace.Contains(new Sphere(p, surfaceGroup.MinDistanceBetweenObjects))) { //found place to create position = p; break; } //} } counter++; } if (position != null) { var objPosition = position.Value + new Vector3(0, 0, positionZ); var objRotation = rotation; var objScale = scale; var surfaceElement = surfaceGroup.GetElement(elementIndex); var surfaceElementMesh = surfaceElement as Component_SurfaceElement_Mesh; if (surfaceElementMesh != null) { var meshInSpace = scene.CreateComponent <Component_MeshInSpace>(enabled: false); meshInSpace.Transform = new Transform(objPosition, objRotation, objScale); //!!!!так копировать? meshInSpace.Mesh = surfaceElementMesh.Mesh; if (meshInSpace.Mesh.Value == null) { meshInSpace.Mesh = ResourceUtility.MeshInvalid; } //!!!!так копировать? if (surfaceElementMesh.ReplaceMaterial.ReferenceSpecified) { meshInSpace.ReplaceMaterial = surfaceElementMesh.ReplaceMaterial; } meshInSpace.Enabled = true; } //add to point container pointContainerFindFreePlace.Add(ref objPosition); } } }
protected virtual void Scene_ViewportUpdateGetCameraSettings(Component_Scene scene, Viewport viewport, ref bool processed) { //copy from Mesh document window code //var camera = scene.CameraEditor.Value; var bounds = scene.CalculateTotalBoundsOfObjectsInSpace(); var cameraLookTo = bounds.GetCenter(); double maxGararite = Math.Max(Math.Max(bounds.GetSize().X, bounds.GetSize().Y), bounds.GetSize().Z); double distance = maxGararite * 2; // 2.3; if (distance < 2) { distance = 2; } double cameraZoomFactor = 1; SphericalDirection cameraDirection = new SphericalDirection(-3.83, -.47); var cameraPosition = cameraLookTo - cameraDirection.GetVector() * distance * cameraZoomFactor; var center = cameraLookTo; // GetSceneCenter(); Vector3 from = cameraPosition; //center + cameraDirection.GetVector() * cameraDistance; Vector3 to = center; Degree fov = 65; // 75; var camera = new Component_Camera(); //camera.AspectRatio = (double)ViewportControl.Viewport.SizeInPixels.X / (double)ViewportControl.Viewport.SizeInPixels.Y; camera.FieldOfView = fov; camera.NearClipPlane = Math.Max(distance / 10000, 0.01); //.1; camera.FarClipPlane = Math.Max(1000, distance * 2); if (mesh.EditorCameraTransform != null) { camera.Transform = mesh.EditorCameraTransform; } else { camera.Transform = new Transform(from, Quaternion.LookAt((to - from).GetNormalize(), Vector3.ZAxis)); } camera.FixedUp = Vector3.ZAxis; viewport.CameraSettings = new Viewport.CameraSettingsClass(viewport, camera); //if( !cameraMode2D ) //{ //var cameraPosition = cameraLookTo - cameraDirection.GetVector() * cameraDistance; //var center = cameraLookTo; //Vector3 from = cameraPosition;//center + cameraDirection.GetVector() * cameraDistance; //Vector3 to = center; //Degree fov = 40;//!!!! 65;// 75; ////!!!! //Component_Camera camera = new Component_Camera(); //camera.AspectRatio = (double)viewport.SizeInPixels.X / (double)viewport.SizeInPixels.Y; //camera.FieldOfView = fov; //camera.NearClipPlane = Math.Max( cameraDistance / 10000, 0.01 );//.1; //camera.FarClipPlane = Math.Max( 1000, cameraDistance * 2 ); //camera.Transform = new Transform( from, Quaternion.LookAt( ( to - from ).GetNormalize(), Vector3.ZAxis ) ); ////camera.Position = from; ////camera.Direction = ( to - from ).GetNormalize(); //camera.FixedUp = Vector3.ZAxis; //viewport.CameraSettings = new Viewport.CameraSettingsClass( viewport, camera ); ////!!!!в методе больше параметров //double aspect = (double)viewport.SizeInPixels.X / (double)viewport.SizeInPixels.Y; //var settings = new Viewport.CameraSettingsClass( viewport, aspect, fov, .1f, 1000, from, ( to - from ).GetNormalize(), Vec3.ZAxis ); //viewport.CameraSettings = settings; //} //else //{ // var from = cameraLookTo + new Vector3( 0, 0, scene.CameraEditor2DPositionZ ); // var to = cameraLookTo; // Component_Camera camera = new Component_Camera(); // camera.AspectRatio = (double)viewport.SizeInPixels.X / (double)viewport.SizeInPixels.Y; // camera.NearClipPlane = 0.01;// Math.Max( cameraInitialDistance / 10000, 0.01 );//.1; // camera.FarClipPlane = 1000;// Math.Max( 1000, cameraInitialDistance * 2 ); // camera.Transform = new Transform( from, Quaternion.LookAt( ( to - from ).GetNormalize(), Vector3.YAxis ) ); // camera.Projection = ProjectionType.Orthographic; // camera.FixedUp = Vector3.YAxis; // //!!!!need consider size by X // camera.Height = cameraInitBounds.GetSize().Y * 1.4; // viewport.CameraSettings = new Viewport.CameraSettingsClass( viewport, camera ); //} processed = true; }
public static Physics2DWorldDataImpl GetWorldData(Component_Scene scene, bool canInit) { return((Physics2DWorldDataImpl)scene.Physics2DGetWorldData(canInit, GetPhysics2DWorldDataInit)); }
///////////////////////////////////////// //Component_Scene public static void PerformGetRenderSceneData(Component_Scene obj, ViewportRenderingContext context) { obj.PerformGetRenderSceneData(context); }
public static (bool found, double positionZ) CalculateObjectPositionZ(Component_Scene scene, Component_GroupOfObjects toGroupOfObjects, double defaultPositionZ, Vector2 position, List <Component> destinationCachedBaseObjects = null) { var ray = new Ray(new Vector3(position, defaultPositionZ + 10000), new Vector3(0, 0, -20000)); if (toGroupOfObjects != null) { //when destination != null double?maxPositionZ = null; var baseObjects = destinationCachedBaseObjects ?? toGroupOfObjects.GetBaseObjects(); foreach (var baseObject in baseObjects) { //terrain var terrain = baseObject as Component_Terrain; if (terrain != null) { if (terrain.GetBounds2().Contains(position)) { var height = terrain.GetHeight(position, false); if (maxPositionZ == null || height > maxPositionZ.Value) { maxPositionZ = height; } } } //mesh in space var meshInSpace = baseObject as Component_MeshInSpace; if (meshInSpace != null) { if (meshInSpace.RayCast(ray, Component_Mesh.CompiledData.RayCastMode.Auto, out var scale, out _)) { var height = ray.GetPointOnRay(scale).Z; if (maxPositionZ == null || height > maxPositionZ.Value) { maxPositionZ = height; } } } //group of objects var groupOfObjects = baseObject as Component_GroupOfObjects; if (groupOfObjects != null) { //!!!! } } if (maxPositionZ != null) { return(true, maxPositionZ.Value); } } else { //when destination == null var result = CalculateCreateObjectPositionByRay(scene, null, ray, false); if (result.found) { return(true, result.position.Z); } } return(false, defaultPositionZ); }
//!!!!подобное для Brush режима //public delegate void CalculateCreateObjectPositionUnderCursorEventDelegate( Component_ObjectInSpace objectInSpace, ref bool found, ref Vector3 position ); //public static event CalculateCreateObjectPositionUnderCursorEventDelegate CalculateCreateObjectPositionUnderCursorEvent; //public class CalculateCreateObjectPositionByRayResult //{ // public bool Found; // public Vector3 Position; // public Component_ObjectInSpace CollidedWith; // public Vector3F Normal; //} public static (bool found, Vector3 position, Component_ObjectInSpace collidedWith) CalculateCreateObjectPositionByRay(Component_Scene scene, Component_ObjectInSpace objectInSpace, Ray ray, bool allowSnap) { //var viewport = ViewportControl.Viewport; //Vector2 mouse; //if( overrideMouse.HasValue ) // mouse = overrideMouse.Value; //else //{ // mouse = viewport.MousePosition; // if( !new Rectangle( 0, 0, 1, 1 ).Contains( mouse ) ) // mouse = new Vector2( 0.5, 0.5 ); //} //Ray ray; //if( overrideRay.HasValue ) // ray = overrideRay.Value; //else // ray = viewport.CameraSettings.GetRayByScreenCoordinates( mouse ); //!!!!? clamp max distance //ray.Direction = ray.Direction.GetNormalize() * 100; //!!!!можно конвекс форму делать вместо бокса Bounds localBounds = new Bounds(); if (objectInSpace != null) { //particle system specific if (!(objectInSpace is Component_ParticleSystemInSpace)) { localBounds = objectInSpace.SpaceBounds.CalculatedBoundingBox - objectInSpace.Transform.Value.Position; } } if (localBounds.GetSize().X < 0.001) { localBounds.Expand(new Vector3(0.001, 0, 0)); } if (localBounds.GetSize().Y < 0.001) { localBounds.Expand(new Vector3(0, 0.001, 0)); } if (localBounds.GetSize().Z < 0.001) { localBounds.Expand(new Vector3(0, 0, 0.001)); } double resultMinScale = 1.01; Component_ObjectInSpace resultMinScaleCollidedWith = null; if (objectInSpace != null) { //when objectInSpace != null Plane[] planes; { var b1 = localBounds + ray.Origin; var b2 = b1 + ray.Direction; var points = CollectionUtility.Merge(b1.ToPoints(), b2.ToPoints()); ConvexHullAlgorithm.Create(points, out planes); } var item = new Component_Scene.GetObjectsInSpaceItem(Component_Scene.GetObjectsInSpaceItem.CastTypeEnum.All, null, true, planes); scene.GetObjectsInSpace(item); foreach (var resultItem in item.Result) { if (objectInSpace != resultItem.Object && !resultItem.Object.GetAllParents(false).Contains(objectInSpace)) { //mesh in space if (resultItem.Object is Component_MeshInSpace meshInSpace) { Vector3[] verticesFull; int[] indices; { var b1 = localBounds + ray.Origin; var b2 = b1 + ray.Direction; var points = CollectionUtility.Merge(b1.ToPoints(), b2.ToPoints()); ConvexHullAlgorithm.Create(points, out verticesFull, out indices); } if (meshInSpace._Intersects(verticesFull, indices)) { double minScale = 1.01; double currentScale = 0.5; //!!!!? const double threshold = 0.00001; double step = 0.25; while (step > threshold) { Vector3[] vertices = new Vector3[verticesFull.Length]; for (int n = 0; n < vertices.Length; n++) { vertices[n] = verticesFull[n] - ray.Direction + ray.Direction * currentScale; } //Vector3[] vertices; //int[] indices; //{ // var b1 = localBounds + ray.Origin; // var b2 = b1 + ray.Direction * currentScale; // var points = CollectionUtility.Merge( b1.ToPoints(), b2.ToPoints() ); // ConvexHullAlgorithm.Create( points, out vertices, out indices ); //} bool intersects = meshInSpace._Intersects(vertices, indices); if (!intersects) { minScale = currentScale; } if (intersects) { currentScale -= step; } else { currentScale += step; } step /= 2; } if (minScale <= 1 && minScale < resultMinScale) { resultMinScale = minScale; resultMinScaleCollidedWith = meshInSpace; } } } //!!!!какие еще } } } else { //when objectInSpace == null var item = new Component_Scene.GetObjectsInSpaceItem(Component_Scene.GetObjectsInSpaceItem.CastTypeEnum.All, null, true, ray); scene.GetObjectsInSpace(item); foreach (var resultItem in item.Result) { //mesh in space if (resultItem.Object is Component_MeshInSpace meshInSpace) { if (meshInSpace.RayCast(ray, Component_Mesh.CompiledData.RayCastMode.Auto, out var scale, out var triangleIndex)) { if (scale <= 1 && scale < resultMinScale) { resultMinScale = scale; resultMinScaleCollidedWith = meshInSpace; //if( triangleIndex != -1 ) //{ //} } } } //!!!!какие еще } } bool found; Vector3 pos; if (resultMinScale <= 1) { found = true; pos = ray.GetPointOnRay(resultMinScale); } else { found = false; pos = ray.Origin + ray.Direction.GetNormalize() * Math.Max(localBounds.GetBoundingSphere().Radius, 1) * 20; } //snap for 2D mode if (scene.Mode.Value == Component_Scene.ModeEnum._2D) { pos.Z = Math.Ceiling(pos.Z); } //snap if (allowSnap) { double snap; //if( Form.ModifierKeys.HasFlag( Keys.Control ) ) snap = ProjectSettings.Get.SceneEditorStepMovement; //else // snap = 0; if (snap != 0) { Vector3 snapVec = new Vector3(snap, snap, snap); pos += snapVec / 2; pos /= snapVec; pos = new Vector3I((int)pos.X, (int)pos.Y, (int)pos.Z).ToVector3(); pos *= snapVec; } } //CalculateCreateObjectPositionUnderCursorEvent?.Invoke( objectInSpace, ref found, ref pos ); return(found, pos, resultMinScaleCollidedWith); //objectToTransform.Transform = new Transform( pos, objectToTransform.Transform.Value.Rotation, objectToTransform.Transform.Value.Scale ); //} //else //{ // var localBounds = objectInSpace.SpaceBounds.CalculatedBoundingBox - objectInSpace.Transform.Value.Position; // //disable object to disable collisions // var disable = ContainsPhysicsBodies( objectInSpace ); // if( disable ) // objectInSpace.Enabled = false; // //!!!!contact group // PhysicsConvexSweepTestItem castItem = new PhysicsConvexSweepTestItem( Matrix4.FromTranslate( ray.Origin ), // Matrix4.FromTranslate( ray.Origin + ray.Direction ), 1, -1, PhysicsConvexSweepTestItem.ModeEnum.OneClosest, localBounds ); // Scene.PhysicsConvexSweepTest( new PhysicsConvexSweepTestItem[] { castItem } ); // //restore disabled object // if( disable ) // objectInSpace.Enabled = true; // Vector3 pos; // if( castItem.Result.Length != 0 ) // pos = castItem.Result[ 0 ].Position; // else // { // pos = ray.Origin + ray.Direction.GetNormalize() * Math.Max( localBounds.GetBoundingSphere().Radius, 1 ) * 20; // } // objectInSpace.Transform = new Transform( pos, objectInSpace.Transform.Value.Rotation, objectInSpace.Transform.Value.Scale ); //} }
public static void Physics2DContactTest(this Component_Scene scene, Physics2DContactTestItem item) { Physics2DContactTest(scene, new Physics2DContactTestItem[] { item }); }
public Component_Import3D CreateForPreviewDisplay(Component_Scene scene, out bool onlyOneMaterial, out Dictionary <Component_Mesh, Transform> transformBySourceMesh) { onlyOneMaterial = false; transformBySourceMesh = new Dictionary <Component_Mesh, Transform>(); var createdObject = (Component_Import3D)Clone(); createdObject.Name = "Import3D"; FixRootReferences(createdObject); scene.AddComponent(createdObject); //create MeshInSpace for one mesh { var mesh = createdObject.GetComponent("Mesh") as Component_Mesh; if (mesh != null) { var objectInSpace = createdObject.CreateComponent <Component_MeshInSpace>(); objectInSpace.Mesh = ReferenceUtility.MakeReference <Component_Mesh>(null, ReferenceUtility.CalculateThisReference(objectInSpace, mesh)); } } //create meshes in space for Meshes { var sourceMeshesGroup = GetComponent("Meshes"); Component_Mesh[] sourceMeshes = null; if (sourceMeshesGroup != null) { sourceMeshes = sourceMeshesGroup.GetComponents <Component_Mesh>(); } var createdMeshesGroup = createdObject.GetComponent("Meshes"); if (createdMeshesGroup != null) { var createdMeshes = createdMeshesGroup.GetComponents <Component_Mesh>(); var positions = new Vector3[createdMeshes.Length]; { if (sourceMeshesGroup != null) { double maxSizeY = 0; foreach (var sourceMesh in sourceMeshesGroup.GetComponents <Component_Mesh>()) { if (sourceMesh.Result != null) { var bounds = sourceMesh.Result.SpaceBounds.CalculatedBoundingBox; var sizeY = bounds.GetSize().Y; if (sizeY > maxSizeY) { maxSizeY = sizeY; } } } var step = maxSizeY * 1.2; var totalSize = (double)(createdMeshes.Length - 1) * step; for (int n = 0; n < createdMeshes.Length; n++) { var positionY = (double)n * step - totalSize / 2; positions[n] = new Vector3(0, positionY, 0); } } } for (int n = 0; n < createdMeshes.Length; n++) { var createdMesh = createdMeshes[n]; var transform = new Transform(positions[n], Quaternion.Identity); var objectInSpace = createdObject.CreateComponent <Component_MeshInSpace>(); objectInSpace.Transform = transform; objectInSpace.Mesh = ReferenceUtility.MakeReference <Component_Mesh>(null, ReferenceUtility.CalculateThisReference(objectInSpace, createdMesh)); if (sourceMeshes != null && sourceMeshes.Length == createdMeshes.Length) { transformBySourceMesh[sourceMeshes[n]] = transform; } } } } //create MeshInSpace for only one material { var material = createdObject.GetComponent("Material") as Component_Material; if (material != null) { var mesh = ProjectSettings.Get.MaterialPreviewMesh.Value; if (mesh != null) { var objectInSpace = createdObject.CreateComponent <Component_MeshInSpace>(); objectInSpace.Mesh = mesh; objectInSpace.ReplaceMaterial = ReferenceUtility.MakeReference <Component_Material>(null, ReferenceUtility.CalculateThisReference(objectInSpace, material)); onlyOneMaterial = true; } } } return(createdObject); }
public static SoundVirtualChannel SoundPlay(Component_Scene attachedToScene, Sound sound, SoundChannelGroup group, double priority, bool paused = false) { if (sound == null) { return(null); } ////!!!!так? //if( ( sound.Mode & SoundModes.Loop ) == 0 && ( sound.Mode & SoundModes.Stream ) == 0 ) //{ // if( attachedToScene != null && listenerCurrentScene != attachedToScene ) // return null; //} //!!!!было ////!!!!так? //if( ( sound.Mode & SoundModes.Loop ) == 0 && ( sound.Mode & SoundModes.Stream ) == 0 ) //{ // List<RealChannel> realChannels = ( sound.Mode & SoundModes.Mode3D ) != 0 ? real3DChannels : real2DChannels; // bool allowPlay = false; // for( int n = 0; n < realChannels.Count; n++ ) // { // VirtualChannel c = realChannels[ n ].CurrentVirtualChannel; // if( c == null || c.Priority < priority ) // { // allowPlay = true; // break; // } // } // if( !allowPlay ) // return null; //} //priority = MathEx.Saturate( priority ); //!!!!было //if( ( sound.Mode & SoundModes.Stream ) != 0 ) //{ // if( sound.playingCount == 1 ) // { // Log.Warning( "SoundSystem: It is impossible to play simultaneously more one channel stream sound." ); // return null; // } //} if (group == null) { group = MasterChannelGroup; } SoundVirtualChannel virtualChannel = new SoundVirtualChannel(); if ((sound.Mode & SoundModes.Mode3D) != 0) { activeVirtual3DChannels.Add(virtualChannel); if (activeVirtual3DChannels.Count > 2048) { Log.Info("SoundSystem: Quantity of active 3D channels > 2048."); } } else { activeVirtual2DChannels.Add(virtualChannel); if (activeVirtual2DChannels.Count > 2048) { Log.Info("SoundSystem: Quantity of active 2D channels > 2048."); } } virtualChannel.SoundPlayInit(attachedToScene, sound, group); virtualChannel.Priority = priority; if (!paused) { virtualChannel.Pause = false; } return(virtualChannel); }
///////////////////////////////////////// public static void Physics2DContactTest(this Component_Scene scene, Physics2DContactTestItem[] items) { var worldData = Physics2DUtility.GetWorldData(scene, false); if (worldData != null) { foreach (var item in items) { var aabb = new AABB(Physics2DUtility.Convert(item.Bounds.Minimum), Physics2DUtility.Convert(item.Bounds.Maximum)); var fixtures = worldData.world.QueryAABB(ref aabb); var result = new List <Physics2DContactTestItem.ResultItem>(fixtures.Count); bool Contains(Component_PhysicalBody2D body, Component_CollisionShape2D shape) { for (int n = 0; n < result.Count; n++) { if (result[n].Body == body && result[n].Shape == shape) { return(true); } } return(false); } PolygonShape polygonShape = null; if (item.Convex != null) { var vertices = new Vertices(item.Convex.Length); foreach (var p in item.Convex) { vertices.Add(Physics2DUtility.Convert(p)); } polygonShape = new PolygonShape(vertices, 0); } foreach (var fixture in fixtures) { if (ShouldCollide(fixture, item)) { bool skip = false; if (polygonShape != null) { fixture.Body.GetTransform(out var bodyTransform); var identity = tainicom.Aether.Physics2D.Common.Transform.Identity; if (!Collision.TestOverlap(polygonShape, 0, fixture.Shape, 0, ref identity, ref bodyTransform)) { skip = true; } } if (!skip) { var shape = fixture.Tag as Component_CollisionShape2D; if (shape != null) { var body = shape.ParentRigidBody; if (!Contains(body, shape)) { var resultItem = new Physics2DContactTestItem.ResultItem(); resultItem.Body = body; resultItem.Shape = shape; result.Add(resultItem); if (item.Mode == Physics2DContactTestItem.ModeEnum.One) { break; } } } } } } item.Result = result.ToArray(); } } else { foreach (var item in items) { item.Result = Array.Empty <Physics2DContactTestItem.ResultItem>(); } } }