/// <summary> /// Adds the specified model to the rear of the 3D scene. /// </summary> /// <param name="model">The rear item in the scene.</param> internal void AddToBack(Viewport2DVisual3D model) { if (AllowTransparency) Children.Insert(1, model); else Children.Add(model); }
internal GeneralTransform2DTo3D(GeneralTransform transform2D, Viewport2DVisual3D containingVisual3D, GeneralTransform3D transform3D) { Visual child = containingVisual3D.Visual; Debug.Assert(child != null, "Going from 2D to 3D containingVisual3D.Visual should not be null"); _transform3D = (GeneralTransform3D)transform3D.GetCurrentValueAsFrozen(); // we also need to go one more level up to handle a transform being placed // on the Viewport2DVisual3D's child GeneralTransformGroup transformGroup = new GeneralTransformGroup(); transformGroup.Children.Add((GeneralTransform)transform2D.GetCurrentValueAsFrozen()); transformGroup.Children.Add((GeneralTransform)child.TransformToOuterSpace().GetCurrentValueAsFrozen()); transformGroup.Freeze(); _transform2D = transformGroup; _positions = containingVisual3D.InternalPositionsCache; _textureCoords = containingVisual3D.InternalTextureCoordinatesCache; _triIndices = containingVisual3D.InternalTriangleIndicesCache; _childBounds = child.CalculateSubgraphRenderBoundsOuterSpace(); }
/// <summary> /// Transform a point /// </summary> /// <param name="inPoint">Input point</param> /// <param name="result">Output point</param> /// <returns>True if the point was transformed successfuly, false otherwise</returns> public bool TryTransform(Point inPoint, out Point3D result) { Point final2DPoint; // assign this now so that we can return false if needed result = new Point3D(); if (!_transform2D.TryTransform(inPoint, out final2DPoint)) { return(false); } Point texCoord = Viewport2DVisual3D.VisualCoordsToTextureCoords(final2DPoint, _childBounds); // need to walk the texture coordinates on the Viewport2DVisual3D // and look for where this point intersects one of them Point3D coordPoint; if (!Viewport2DVisual3D.Get3DPointFor2DCoordinate(texCoord, out coordPoint, _positions, _textureCoords, _triIndices)) { return(false); } if (!_transform3D.TryTransform(coordPoint, out result)) { return(false); } return(true); }
/// <summary> /// Adds the specified model to the front of the 3D scene. /// </summary> /// <param name="model">The front item in the scene.</param> internal void AddToFront(Viewport2DVisual3D model) { if (this.AllowTransparency) base.Children.Add(model); else base.Children.Insert(1, model); }
internal static void OnGeometryChanged(Object sender, DependencyPropertyChangedEventArgs e) { Viewport2DVisual3D viewport2DVisual3D = ((Viewport2DVisual3D)sender); viewport2DVisual3D.InvalidateAllCachedValues(); if (!e.IsASubPropertyChange) { ((GeometryModel3D)viewport2DVisual3D.Visual3DModel).Geometry = viewport2DVisual3D.Geometry; } }
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.PerspectiveCamera = ((System.Windows.Media.Media3D.PerspectiveCamera)(target)); return; case 2: this.containerUIElement3D = ((System.Windows.Media.Media3D.ContainerUIElement3D)(target)); return; case 3: this.FrontViewport2DVisual3D = ((System.Windows.Media.Media3D.Viewport2DVisual3D)(target)); return; case 4: this.newS = ((System.Windows.Controls.Button)(target)); #line 169 "..\..\..\Transform\Viewport3DTransform.xaml" this.newS.Click += new System.Windows.RoutedEventHandler(this.newS_Click); #line default #line hidden return; case 5: this.BackViewport2DVisual3D = ((System.Windows.Media.Media3D.Viewport2DVisual3D)(target)); return; case 6: this.setS = ((System.Windows.Controls.Button)(target)); #line 215 "..\..\..\Transform\Viewport3DTransform.xaml" this.setS.Click += new System.Windows.RoutedEventHandler(this.setS_Click); #line default #line hidden return; case 7: this.ViewLight = ((System.Windows.Media.Media3D.AmbientLight)(target)); return; case 8: this.DisplayGrid = ((System.Windows.Controls.Grid)(target)); return; case 9: this.DisPlayControl = ((System.Windows.Controls.UserControl)(target)); return; } this._contentLoaded = true; }
private void AddUIP3DPlane() { var rectangle = SimpleGeometry3D.CreateRectangle(2, 3); var viewport2D = new Viewport2DVisual3D(); viewport2D.Geometry = rectangle; viewport2D.Visual = _soundVisualizer; var material = new DiffuseMaterial { Brush = Brushes.Black }; Viewport2DVisual3D.SetIsVisualHostMaterial(material, true); viewport2D.Material = material; viewport2D.Transform = new TranslateTransform3D(0, -0.5, 0); _scene.Add2DUI(viewport2D); }
internal HitTestResultBehavior RaiseCallback(HitTestResultCallback resultCallback, HitTestFilterCallback filterCallback, HitTestResultBehavior lastResult, double distanceAdjustment) { results.Sort(RayHitTestResult.CompareByDistanceToRayOrigin); for (int i = 0, count = results.Count; i < count; i++) { RayHitTestResult result = results[i]; result.SetDistanceToRayOrigin(result.DistanceToRayOrigin + distanceAdjustment); Viewport2DVisual3D viewport2DVisual3D = result.VisualHit as Viewport2DVisual3D; if (viewport2DVisual3D != null) { Point intersectionPoint; Visual viewport2DVisual3DChild = viewport2DVisual3D.Visual; if (viewport2DVisual3DChild != null) { if (Viewport2DVisual3D.GetIntersectionInfo(result, out intersectionPoint)) { // convert the resulting point to visual coordinates Point visualPoint = Viewport2DVisual3D.TextureCoordsToVisualCoords(intersectionPoint, viewport2DVisual3DChild); GeneralTransform gt = viewport2DVisual3DChild.TransformToOuterSpace().Inverse; Point pointOnChild; if (gt != null && gt.TryTransform(visualPoint, out pointOnChild)) { HitTestResultBehavior behavior2D = viewport2DVisual3DChild.HitTestPoint(filterCallback, resultCallback, new PointHitTestParameters(pointOnChild)); if (behavior2D == HitTestResultBehavior.Stop) { return(HitTestResultBehavior.Stop); } } } } } HitTestResultBehavior behavior = resultCallback(results[i]); if (behavior == HitTestResultBehavior.Stop) { return(HitTestResultBehavior.Stop); } } return(lastResult); }
public void CreateVisual3D(Model model) { UI ui = new UI(UITemplate); Viewport2DVisual3D visual = new Viewport2DVisual3D(); visual.Geometry = Geometry; visual.Visual = ui.Visual; EmissiveMaterial material = new EmissiveMaterial(Brushes.White); Viewport2DVisual3D.SetIsVisualHostMaterial(material, true); visual.Material = material; model.Children.Add(visual); }
internal static void OnVisualChanged(Object sender, DependencyPropertyChangedEventArgs e) { Viewport2DVisual3D viewport2DVisual3D = ((Viewport2DVisual3D)sender); // remove the old parent, add on a new one Visual oldValue = (Visual)e.OldValue; Visual newValue = (Visual)e.NewValue; if (oldValue != newValue) { // // The following code deals with properly setting up the new child to have its inheritance context // only point towards this Viewport2DVisual3D. // // When we add the new visual as a child, if that visual is an FE (which most will be) we expect it to // clear the inheritance context (IC) since it has a visual parent. In the case of a non-FE they don't // deal with ICs anyway, so they should have a null IC. The Assert that follows then guards against // the child not having a null inheritance context. // // We then set the target Visual on the internal brush to be this new visual. Since when we created // the brush we set it to not be an inheritance context, the InheritanceContext should still be null. // // We become the IC after returning from this function, since the function that calls this change handler // will set us as the IC. // if (viewport2DVisual3D.CacheMode as BitmapCache != null) { viewport2DVisual3D.InternalBitmapCacheBrush.Target = newValue; Debug.Assert((newValue == null || newValue.InheritanceContext == null), "Expected BitmapCacheBrush to remove the InheritanceContext on newValue"); } else { // Add ourselves as the parent of the object viewport2DVisual3D.RemoveVisualChild(oldValue); viewport2DVisual3D.AddVisualChild(newValue); Debug.Assert((newValue == null || newValue.InheritanceContext == null), "Expected AddVisualChild to remove the InheritanceContext on newValue"); // Change the brush's target viewport2DVisual3D.InternalVisualBrush.Visual = newValue; // setting the visual brush to use this new child should not invalidate our previous condition Debug.Assert((newValue == null || newValue.InheritanceContext == null), "Expected the InternalVisualBrush not to set the InheritanceContext"); } } }
private CubeNavigator() { cubeNavViewport = mainWindow.CubeNavViewport; //cubeNavModel = mainWindow.CubeNavModel; cubeFront = mainWindow.CubeFront; cubeBack = mainWindow.CubeBack; cubeLeft = mainWindow.CubeLeft; cubeRight = mainWindow.CubeRight; cubeUp = mainWindow.CubeUp; cubeDown = mainWindow.CubeDown; cubeNavViewport.PreviewMouseDown += cubeNavViewport_ButtonDown; mainWindow.PreviewMouseMove += cubeNavViewport_MouseMove; mainWindow.PreviewMouseUp += cubeNavViewport_ButtonUp; }
public Cube3D() { Canvas.SetLeft(this,0); Canvas.SetTop(this,0); this.Width=733; this.Height = 400; this.ClipToBounds = true; //add camera PerspectiveCamera myPCamera = new PerspectiveCamera(); myPCamera.Position = new Point3D(0, 30, 90); myPCamera.LookDirection = new Vector3D(0, -20, -90); myPCamera.FieldOfView = 80; this.Camera = myPCamera; //add light ModelVisual3D mv3dLight = new ModelVisual3D(); DirectionalLight myDirLight = new DirectionalLight(); myDirLight.Color = Colors.White; myDirLight.Direction = new Vector3D(-2, -3, -1); mv3dLight.Content = myDirLight; this.Children.Add(mv3dLight); //add material and mesh geometry Viewport2DVisual3D vpMaterial = new Viewport2DVisual3D(); DiffuseMaterial dm = new DiffuseMaterial(); dm.Brush = Brushes.Transparent; vpMaterial.Material = dm; MeshGeometry3D vpg = new MeshGeometry3D(); vpg.Positions.Add(new Point3D(-55,0,-30)); vpg.Positions.Add(new Point3D(-55,0,30)); vpg.Positions.Add(new Point3D(55,0,30)); vpg.Positions.Add(new Point3D(55,0,-30)); vpg.TextureCoordinates.Add(new Point(0,0)); vpg.TextureCoordinates.Add(new Point(0,1)); vpg.TextureCoordinates.Add(new Point(1,1)); vpg.TextureCoordinates.Add(new Point(1,0)); vpg.TriangleIndices.Add(0); vpg.TriangleIndices.Add(1); vpg.TriangleIndices.Add(2); vpg.TriangleIndices.Add(2); vpg.TriangleIndices.Add(3); vpg.TriangleIndices.Add(0); vpMaterial.Geometry = vpg; this.Children.Add(vpMaterial); this.Loaded += new RoutedEventHandler(OnLoad); }
/// <summary> /// When overridden in a derived class, is invoked whenever application code or internal processes call <see cref="M:System.Windows.FrameworkElement.ApplyTemplate"/>. /// </summary> public override void OnApplyTemplate() { _viewport = GetTemplateChild("PART_Viewport") as Viewport3D; _camera = GetTemplateChild("PART_Camera") as PerspectiveCamera; _frontContent = GetTemplateChild("PART_FrontContent") as Border; _frontModel = GetTemplateChild("PART_FrontModel") as Viewport2DVisual3D; _backContent = GetTemplateChild("PART_BackContent") as Border; _backModel = GetTemplateChild("PART_BackModel") as Viewport2DVisual3D; _scale = GetTemplateChild("PART_Scale") as ScaleTransform3D; _rotate = GetTemplateChild("PART_Rotate") as RotateTransform3D; _quaternion = GetTemplateChild("PART_Quaternion") as QuaternionRotation3D; _fixedContainer = GetTemplateChild("PART_FixedContainer") as Border; _fixedHiddenContainer = GetTemplateChild("PART_FixedHiddenContainer") as Border; _fixedTransform = GetTemplateChild("PART_FixedTransform") as RotateTransform; _directionalLights = GetTemplateChild("PART_DirectionalLights") as ModelVisual3D; _ambientLights = GetTemplateChild("PART_AmbientLights") as ModelVisual3D; SizeChanged += (sender, e) => UpdateBounds(); _frontContent.SizeChanged += (sender, e) => UpdateBounds(); _backContent.SizeChanged += (sender, e) => UpdateBounds(); UpdateBounds(); UpdateRotation(); UpdateLights(); UpdateCacheInvalidationThresholdMaximum(); UpdateCacheInvalidationThresholdMinimum(); base.OnApplyTemplate(); }
/// <summary> /// Returns the index of the specified model where 0 is the front item. /// If the model is not in the scene, returns -1. /// </summary> internal int GetVisualIndex(Viewport2DVisual3D model) { int modelIndex = Children.IndexOf(model); if (modelIndex < 0) return -1; if (AllowTransparency) return ModelCount - modelIndex; return modelIndex - 1; }
public void Add2DUI(Viewport2DVisual3D viewport2D) { Viewport.Children.Add(viewport2D); }
private void BuildFront() { //构造图形 var geometry = new MeshGeometry3D(); double x = CubeLength / 2; double y = CubeHeight / 2; double z = CubeWidth / 2; geometry.Positions = new Point3DCollection((new Point3D[] { new Point3D(-x, -y,z), //左下角 new Point3D(x,-y,z), //右下角 new Point3D(x,y,z), //右上角 new Point3D(-x,y,z) //左上角 })); //三角形构造,影响呈现的正反面 geometry.TriangleIndices = new Int32Collection(new int[] { 0, 1, 2, 2, 3, 0 }); //纹理 geometry.TextureCoordinates = new PointCollection(new Point[] { new Point(0, 1), new Point(1, 1), new Point(1, 0), new Point() }); //如果已经有了,只更新图形 if (frontViewPort != null) { frontViewPort.Geometry = geometry; return; } //正面 frontViewPort = new Viewport2DVisual3D(); frontViewPort.Geometry = geometry; if (FrontContent != null) { frontViewPort.Visual = FrontContent; } else { var grid = new Grid(); grid.Children.Add(new TextBlock() { Text = "正面", Background = Brushes.BlueViolet }); frontViewPort.Visual = grid; } frontViewPort.Material = material; Children.Add(frontViewPort); }
/// <summary> /// Returns the index of the specified model where 0 is the front item. /// If the model is not in the scene, returns -1. /// </summary> internal int GetVisualIndex(Viewport2DVisual3D model) { int modelIndex = base.Children.IndexOf(model); if (modelIndex < 0) return -1; if (this.AllowTransparency) return this.ModelCount - modelIndex; else return modelIndex - 1; }
private Visual3D EnsureChild(Visual3D currentChild, Shape3DMaterial material) { Visual3D newChild = null; if (material != null) { if (material.HasElement) { // We need a Viewport2DVisual3D to display an element. if(currentChild is Viewport2DVisual3D) { newChild = currentChild; } else { //Viewbox viewbox = new Viewbox(); //viewbox.StretchDirection = StretchDirection.Both; //viewbox.Stretch = Stretch.Fill; Border border = new Border(); border.UseLayoutRounding = true; border.Background = Brushes.Green; //border.Child = viewbox; Viewport2DVisual3D viewport = new Viewport2DVisual3D(); viewport.Visual = border; newChild = viewport; } // Set the appropriate caching strategy. CacheScale cacheScale = CacheScale; if (cacheScale == null) { // Remove any VisualBrush caching. RenderOptions.SetCachingHint(newChild, CachingHint.Unspecified); // Remove any BitmapCache. ((Viewport2DVisual3D)newChild).CacheMode = null; } else if (cacheScale.IsAuto) { // Remove any BitmapCache. ((Viewport2DVisual3D)newChild).CacheMode = null; // Specify VisualBrush caching with 2x min and max // thresholds. RenderOptions.SetCachingHint(newChild, CachingHint.Cache); RenderOptions.SetCacheInvalidationThresholdMinimum(newChild, 0.5); RenderOptions.SetCacheInvalidationThresholdMaximum(newChild, 2.0); } else { // Remove any VisualBrush caching. RenderOptions.SetCachingHint(newChild, CachingHint.Unspecified); // Set a BitmapCache with the appropriate scale. BitmapCache bitmapCache = ((Viewport2DVisual3D)newChild).CacheMode as BitmapCache; if (bitmapCache == null) { ((Viewport2DVisual3D)newChild).CacheMode = new BitmapCache(cacheScale.Scale); } else { bitmapCache.RenderAtScale = cacheScale.Scale; } } } else { Debug.Assert(material.HasMaterial); // We need a ModelVisual3D to display the material. if(currentChild is ModelVisual3D) { Debug.Assert(((ModelVisual3D)currentChild).Content is GeometryModel3D); newChild = currentChild; } else { newChild = new ModelVisual3D(); ((ModelVisual3D)newChild).Content = new GeometryModel3D(); } } } return newChild; }
private static void OnCachingHintChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Viewport2DVisual3D viewport2D = (Viewport2DVisual3D)d; RenderOptions.SetCachingHint(viewport2D._visualBrush, (CachingHint)e.NewValue); }
private FrameworkElement CreateVisualChild() { MeshGeometry3D simpleQuad = new MeshGeometry3D() { Positions = new Point3DCollection(_mesh), TextureCoordinates = new PointCollection(_texCoords), TriangleIndices = new Int32Collection(_indices) }; // Front material is interactive, back material is not. Material frontMaterial = new DiffuseMaterial(Brushes.White); frontMaterial.SetValue(Viewport2DVisual3D.IsVisualHostMaterialProperty, true); VisualBrush vb = new VisualBrush(_logicalChild); SetCachingForObject(vb); // big perf wins by caching!! Material backMaterial = new DiffuseMaterial(vb); _rotationTransform.Rotation = _quaternionRotation; var xfGroup = new Transform3DGroup() { Children = { _scaleTransform, _rotationTransform } }; GeometryModel3D backModel = new GeometryModel3D() { Geometry = simpleQuad, Transform = xfGroup, BackMaterial = backMaterial }; Model3DGroup m3dGroup = new Model3DGroup() { Children = { new DirectionalLight(Colors.White, new Vector3D(0, 0, -1)), new DirectionalLight(Colors.White, new Vector3D(0.1, -0.1, 1)), backModel } }; // Non-interactive Visual3D consisting of the backside, and two lights. ModelVisual3D mv3d = new ModelVisual3D() { Content = m3dGroup }; // Interactive frontside Visual3D Viewport2DVisual3D frontModel = new Viewport2DVisual3D() { Geometry = simpleQuad, Visual = _logicalChild, Material = frontMaterial, Transform = xfGroup }; // Cache the brush in the VP2V3 by setting caching on it. Big perf wins. SetCachingForObject(frontModel); // Scene consists of both the above Visual3D's. _viewport3d = new Viewport3D() { ClipToBounds = false, Children = { mv3d, frontModel } }; UpdateRotation(); return _viewport3d; }
private void SetupModel() { Visual front = null; Visual back = null; if (frontVisual3D != null) { front = frontVisual3D.Visual; frontVisual3D.Visual = null; } if (backVisual3D != null) { back = backVisual3D.Visual; backVisual3D.Visual = null; } frontVisual3D = new Viewport2DVisual3D { Geometry = mesh, Material = visualHostMaterial, }; backVisual3D = new Viewport2DVisual3D { Geometry = mesh, Material = visualHostMaterial, Transform = new RotateTransform3D(new AxisAngleRotation3D(SpinAxis == Orientation.Vertical ? AxisY : AxisX, 180)) }; rotation.Axis = SpinAxis == Orientation.Vertical ? AxisY : AxisX; if (front != null) frontVisual3D.Visual = front; if (back != null) backVisual3D.Visual = back; model.Children.Clear(); model.Children.Add(frontVisual3D); model.Children.Add(backVisual3D); InvalidateMeasure(); }
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.Side1 = ((System.Windows.Media.Media3D.Viewport2DVisual3D)(target)); return; case 2: this.rot = ((System.Windows.Media.Media3D.AxisAngleRotation3D)(target)); return; case 3: this.Side2 = ((System.Windows.Media.Media3D.Viewport2DVisual3D)(target)); return; case 4: this.rot2 = ((System.Windows.Media.Media3D.AxisAngleRotation3D)(target)); return; } this._contentLoaded = true; }
/// <summary> /// Adjusts a 3D model's location and opacity. /// </summary> void ConfigureModel(Viewport2DVisual3D model, int index) { // We begin "null animations" to unapply any active animations. var trans = model.Transform as TranslateTransform3D; trans.BeginAnimation(TranslateTransform3D.OffsetXProperty, null); trans.BeginAnimation(TranslateTransform3D.OffsetYProperty, null); trans.BeginAnimation(TranslateTransform3D.OffsetZProperty, null); var offsets = this.GetModelOffsets(index); trans.OffsetX = offsets.X; trans.OffsetY = offsets.Y; trans.OffsetZ = offsets.Z; var elem = model.Visual as UIElement; elem.BeginAnimation(UIElement.OpacityProperty, null); elem.Opacity = this.AutoAdjustOpacity ? this.GetElementOpacity(index) : 1.0; }
/// <summary> /// Tears down the current 3D scene and constructs a new one /// where the specified model is the front object in view. /// </summary> void BuildScene(Viewport2DVisual3D frontModel) { _viewport.RemoveAllModels(); // Add in some 3D models, starting with the one in front. var current = frontModel; for (int i = 0; _viewport.ModelCount < this.MaxVisibleModels; ++i) { this.ConfigureModel(current, i); _viewport.AddToBack(current); current = this.GetNextModel(current); if (_viewport.Children.Contains(current)) break; } }
/// <summary> /// Construct a new display object. /// </summary> /// <param name="Key">The key it is stored at.</param> /// <param name="pRenderer">The renderer which created it.</param> internal Display(object Key, Renderer pRenderer) { // Store the renderer. this.Renderer = pRenderer; this.Key = Key; // Identities. HomographyTransform = new MatrixTransform3D(); // Create the model visual. Viewport2DVisual3D = new Viewport2DVisual3D(); // Geom (create a texturemapped rectangle). var pMeshGeometry3D = new MeshGeometry3D(); pMeshGeometry3D.Positions.Add(new Point3D(0, 0, 0)); pMeshGeometry3D.Positions.Add(new Point3D(0, 1, 0)); pMeshGeometry3D.Positions.Add(new Point3D(1, 0, 0)); pMeshGeometry3D.Positions.Add(new Point3D(1, 1, 0)); pMeshGeometry3D.TextureCoordinates.Add(new Point(0, 0)); pMeshGeometry3D.TextureCoordinates.Add(new Point(1, 0)); pMeshGeometry3D.TextureCoordinates.Add(new Point(0, 1)); pMeshGeometry3D.TextureCoordinates.Add(new Point(1, 1)); //pMeshGeometry3D.TextureCoordinates.Add(new Point(0, 1)); //pMeshGeometry3D.TextureCoordinates.Add(new Point(0, 0)); //pMeshGeometry3D.TextureCoordinates.Add(new Point(1, 1)); //pMeshGeometry3D.TextureCoordinates.Add(new Point(1, 0)); pMeshGeometry3D.TriangleIndices.Add(0); pMeshGeometry3D.TriangleIndices.Add(2); pMeshGeometry3D.TriangleIndices.Add(1); pMeshGeometry3D.TriangleIndices.Add(2); pMeshGeometry3D.TriangleIndices.Add(3); pMeshGeometry3D.TriangleIndices.Add(1); Viewport2DVisual3D.Geometry = pMeshGeometry3D; // Create a visual brush which we apply to our material. VisualBrush = new VisualBrush(); VisualBrush.Visual = Content; // Create a material which wraps this brush. var pDiffuse = new DiffuseMaterial(); pDiffuse.Brush = Brushes.White; Viewport2DVisual3D.SetIsVisualHostMaterial(pDiffuse, true); Viewport2DVisual3D.Material = new DiffuseMaterial(VisualBrush); Viewport2DVisual3D.Visual = Content; // Transform. Viewport2DVisual3D.Transform = HomographyTransform; }
/// <summary> /// Get a display by looking up it's visual 3d model. This is useful for handling hit test results. /// </summary> /// <param name="pVisual3D">The 3D model.</param> /// <returns>Null if not found or the display reference if found.</returns> public Display GetDisplayByViewport(Viewport2DVisual3D pVisual3D) { // For each display, find a matching visual. foreach (var d in dDisplays.Values) { if (d.Viewport2DVisual3D == pVisual3D) return d; } return null; }
internal static void OnMaterialPropertyChanged(Object sender, DependencyPropertyChangedEventArgs e) { Viewport2DVisual3D viewport2DVisual3D = ((Viewport2DVisual3D)sender); viewport2DVisual3D.GenerateMaterial(); }
internal static void OnCacheModeChanged(Object sender, DependencyPropertyChangedEventArgs e) { Viewport2DVisual3D viewport2DVisual3D = ((Viewport2DVisual3D)sender); BitmapCache oldValue = (CacheMode)e.OldValue as BitmapCache; BitmapCache newValue = (CacheMode)e.NewValue as BitmapCache; if (oldValue != newValue) { viewport2DVisual3D.InternalBitmapCacheBrush.BitmapCache = newValue; // // The BitmapCacheBrush doesn't point directly at the Visual like the VisualBrush does, // since BitmapCacheBrush ignores most properties on a Visual by design. In order for // those properties to be respected to match the internal VisualBrush's behavior, we insert // a dummy Visual node between the V2DV3D and its 2D Visual. We then target the dummy // node with the brush instead. // if (oldValue == null) { // // If we are swapping from using the VisualBrush to using the BitmapCacheBrush... // // Remove the visual child from the V2DV3D and add the dummy child. viewport2DVisual3D.RemoveVisualChild(viewport2DVisual3D.Visual); viewport2DVisual3D.AddVisualChild(viewport2DVisual3D.InternalBitmapCacheBrush.InternalTarget); Debug.Assert((viewport2DVisual3D.InternalBitmapCacheBrush.InternalTarget == null || viewport2DVisual3D.InternalBitmapCacheBrush.InternalTarget.InheritanceContext == null), "Expected AddVisualChild to remove the InheritanceContext on InternalTarget"); // Swap the brush pointing to the visual. The cache brush will re-parent the visual to the dummy. viewport2DVisual3D.InternalVisualBrush.Visual = null; viewport2DVisual3D.InternalBitmapCacheBrush.Target = viewport2DVisual3D.Visual; // setting the cache brush to use this new child should not invalidate our previous condition Debug.Assert((viewport2DVisual3D.InternalBitmapCacheBrush.InternalTarget == null || viewport2DVisual3D.InternalBitmapCacheBrush.InternalTarget.InheritanceContext == null), "Expected the InternalBitmapCacheBrush not to set the InheritanceContext"); } if (newValue == null) { // // If we are swapping from using the BitmapCacheBrush to using the VisualBrush... // // Swap the brush pointing to the visual. The cache brush will remove the dummy as the parent // of the visual. viewport2DVisual3D.InternalBitmapCacheBrush.Target = null; viewport2DVisual3D.InternalVisualBrush.Visual = viewport2DVisual3D.Visual; // Remove the dummy child and re-add the visual as the V2DV3D's child. viewport2DVisual3D.RemoveVisualChild(viewport2DVisual3D.InternalBitmapCacheBrush.InternalTarget); viewport2DVisual3D.AddVisualChild(viewport2DVisual3D.Visual); Debug.Assert((viewport2DVisual3D.Visual == null || viewport2DVisual3D.Visual.InheritanceContext == null), "Expected AddVisualChild to remove the InheritanceContext on Visual"); } // If we changed from using one brush to the other we need to regenerate the Material. if (oldValue == null || newValue == null) { viewport2DVisual3D.GenerateMaterial(); } } }
// // CONSTRUCTOR // public MosaicFootprint(BitmapImage image, double xmin, double ymin, double xmax, double ymax, double height, ModelVisual3D highlightlines, ModelVisual3D selectedlines) { // this.Attributes = new Dictionary<string, object>(); this.Image = image; this.XMin = xmin; this.YMin = ymin; this.XMax = xmax; this.YMax = ymax; this.Height = height; this.HighlightLines = highlightlines; this.SelectedLines = selectedlines; // Define normals Vector3DCollection normals = new Vector3DCollection(); normals.Add(new Vector3D(0, 0, 1)); normals.Add(new Vector3D(0, 0, 1)); normals.Add(new Vector3D(0, 0, 1)); normals.Add(new Vector3D(0, 0, 1)); normals.Add(new Vector3D(0, 0, 1)); normals.Add(new Vector3D(0, 0, 1)); // Define vertex positions Point3DCollection positions = new Point3DCollection(); positions.Add(new Point3D(this.XMin, this.YMin, this.Height)); positions.Add(new Point3D(this.XMin, this.YMax, this.Height)); positions.Add(new Point3D(this.XMax, this.YMax, this.Height)); positions.Add(new Point3D(this.XMax, this.YMin, this.Height)); // Define textures PointCollection textureCoordinates = new PointCollection(); textureCoordinates.Add(new Point(0, 1)); textureCoordinates.Add(new Point(0, 0)); textureCoordinates.Add(new Point(1, 0)); textureCoordinates.Add(new Point(1, 1)); // Define triangles Int32Collection triangleIndices = new Int32Collection(); triangleIndices.Add(0); triangleIndices.Add(3); triangleIndices.Add(2); triangleIndices.Add(2); triangleIndices.Add(1); triangleIndices.Add(0); // Create Border (up facing) with image texture this.Element = new Border() { Cursor = Cursors.Hand, Height = 100, Width = 100, Background = new ImageBrush() { ImageSource = this.Image, Stretch = Stretch.Fill } }; this.Element.MouseEnter += (s, e) => { this.IsMouseOver = true; }; this.Element.MouseLeave += (s, e) => { this.IsMouseOver = false; }; // Create Viewport2DVisual3D from Border Viewport2DVisual3D top = new Viewport2DVisual3D() { Geometry = new MeshGeometry3D() { Normals = normals, Positions = positions, TextureCoordinates = textureCoordinates, TriangleIndices = triangleIndices }, Material = new DiffuseMaterial() { Brush = new SolidColorBrush() { Color = Colors.White }, AmbientColor = Colors.White }, Visual = this.Element }; Viewport2DVisual3D.SetIsVisualHostMaterial(top.Material, true); // Create down facing texture ModelUIElement3D bottom = new ModelUIElement3D() { IsHitTestVisible = true, Model = new GeometryModel3D() { Geometry = new MeshGeometry3D() { Normals = normals, Positions = positions, TextureCoordinates = textureCoordinates, TriangleIndices = triangleIndices }, BackMaterial = new DiffuseMaterial() { Brush = new SolidColorBrush() { Color = Colors.LightGray } } } }; // Create Model ModelVisual3D model = new ModelVisual3D(); model.Children.Add(top); model.Children.Add(bottom); this.ModelVisual = model; }
private static void OnCacheInvalidationThresholdMaximumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Viewport2DVisual3D viewport2D = (Viewport2DVisual3D)d; RenderOptions.SetCacheInvalidationThresholdMaximum(viewport2D._visualBrush, (double)e.NewValue); }
private void BuildBack() { var geometry = new MeshGeometry3D(); double x = CubeLength / 2; double y = CubeHeight / 2; double z = CubeWidth / 2; geometry.Positions = new Point3DCollection((new Point3D[] { new Point3D(-x, -y,-z), //左下角 new Point3D(x,-y,-z), //右下角 new Point3D(x,y,-z), //右上角 new Point3D(-x,y,-z) //左上角 })); //三角形构造,影响呈现的正反面 geometry.TriangleIndices = new Int32Collection(new int[] { 0, 2, 1, 0, 3, 2 }); //纹理 geometry.TextureCoordinates = new PointCollection(new Point[] { new Point(0, 0), new Point(1, 0), new Point(1, 1), new Point(0, 1) }); if (backViewPort != null) { backViewPort.Geometry = geometry; return; } //背面 backViewPort = new Viewport2DVisual3D(); backViewPort.Geometry = geometry; var grid = new Grid(); if (BackContent != null) backViewPort.Visual = BackContent; else { grid.Children.Add(new TextBlock() { Text = "背面", Background = Brushes.Blue }); backViewPort.Visual = grid; } backViewPort.Material = material; Children.Add(backViewPort); }
/// <summary> /// Constructor /// </summary> /// <param name="visual3D">The Visual3D that contains the 2D visual</param> /// <param name="fromVisual">The visual on the Visual3D</param> internal GeneralTransform2DTo3DTo2D(Viewport2DVisual3D visual3D, Visual fromVisual) { IsInverse = false; // get a copy of the geometry information - we store our own model to reuse hit // test code on the GeometryModel3D _geometry = new MeshGeometry3D(); _geometry.Positions = visual3D.InternalPositionsCache; _geometry.TextureCoordinates = visual3D.InternalTextureCoordinatesCache; _geometry.TriangleIndices = visual3D.InternalTriangleIndicesCache; _geometry.Freeze(); Visual visual3Dchild = visual3D.Visual; // Special case - Setting CacheMode on V2DV3D causes an internal switch from using a VisualBrush // to using a BitmapCacheBrush. It also introduces an extra 2D Visual in the Visual tree above // the V2DV3D.Visual, but this extra node has no effect on transforms and can safely be ignored. // The transform returned will be identical to the one created for calling TransformTo* with // the V2DV3D.Visual itself. Visual descendentVisual = (fromVisual == visual3Dchild._parent) ? visual3Dchild : fromVisual; // get a copy of the size of the visual brush and the rect on the // visual that the transform is going to/from _visualBrushBounds = visual3Dchild.CalculateSubgraphRenderBoundsOuterSpace(); _visualBounds = descendentVisual.CalculateSubgraphRenderBoundsInnerSpace(); // get the transform that will let us go from the fromVisual to its last 2D // parent before it reaches the 3D part of the graph (i.e. visual3D.Child) GeneralTransformGroup transformGroup = new GeneralTransformGroup(); transformGroup.Children.Add(descendentVisual.TransformToAncestor(visual3Dchild)); transformGroup.Children.Add(visual3Dchild.TransformToOuterSpace()); transformGroup.Freeze(); _transform2D = transformGroup; // store the inverse as well _transform2DInverse = (GeneralTransform)_transform2D.Inverse; if (_transform2DInverse != null) { _transform2DInverse.Freeze(); } // make a copy of the camera and other values on the Viewport3D Viewport3DVisual viewport3D = (Viewport3DVisual)VisualTreeHelper.GetContainingVisual2D(visual3D); _camera = viewport3D.Camera; if (_camera != null) { _camera = (Camera)viewport3D.Camera.GetCurrentValueAsFrozen(); } _viewSize = viewport3D.Viewport.Size; _boundingRect = viewport3D.ComputeSubgraphBounds3D(); _objectToViewport = visual3D.TransformToAncestor(viewport3D); // if the transform was not possible, it could be null - check before freezing if (_objectToViewport != null) { _objectToViewport.Freeze(); } // store the needed transformations for the various operations _worldTransformation = M3DUtil.GetWorldTransformationMatrix(visual3D); _validEdgesCache = null; }
/// <summary> /// Returns an interactive 3D model that hosts /// the specified UIElement. /// </summary> Viewport2DVisual3D BuildModel(UIElement element) { var model = new Viewport2DVisual3D { Geometry = new MeshGeometry3D { TriangleIndices = new Int32Collection( new int[] { 0, 1, 2, 2, 3, 0 }), TextureCoordinates = new PointCollection( new Point[] { new Point(0, 1), new Point(1, 1), new Point(1, 0), new Point(0, 0) }), Positions = new Point3DCollection( new Point3D[] { new Point3D(-1, -1, 0), new Point3D(+1, -1, 0), new Point3D(+1, +1, 0), new Point3D(-1, +1, 0) }) }, Material = new DiffuseMaterial() { }, Transform = new TranslateTransform3D(), // Host the 2D element in the 3D model. Visual = element }; Viewport2DVisual3D.SetIsVisualHostMaterial(model.Material, true); return model; }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { try { //_quick = new BackdropQuick(); //_quick.Show(); //_quick.ValueChanged += _quick_ValueChanged; //NOTE: This MUST be set in loaded, or keyboard events get very flaky (even if the usercontrol has focus, something //inside of it must also have focus) lblFocusable.Focus(); // Setting these up now so that the order stays consistent (so that semitransparency will work) #region Back visual _backVisual = new ModelVisual3D(); if (_graphic == null) { _backVisual.Content = GetBlankModel(); } else { _backVisual.Content = _graphic.Model; } _viewport.Children.Add(_backVisual); #endregion #region 2D panel DiffuseMaterial diffuse = new DiffuseMaterial(Brushes.White); Viewport2DVisual3D.SetIsVisualHostMaterial(diffuse, true); grd3D = new Grid(); grd3D.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(2, GridUnitType.Star) }); grd3D.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(.5, GridUnitType.Star) }); grd3D.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); Grid.SetColumn(pnlLeft, 0); Grid.SetColumn(pnlDetail, 2); grd3D.Children.Add(pnlLeft); grd3D.Children.Add(pnlDetail); _visual2D3D = new Viewport2DVisual3D(); _visual2D3D.Material = diffuse; //_visual2D3D.Geometry = GetGeometry(_quick.CylinderNumSegments, _quick.CylinderThetaOffset, _quick.CylinderHeight, _quick.CylinderRadius, _quick.CylinderTranslate); _visual2D3D.Geometry = GetGeometry(NUMSEGMENTS, THETA, HEIGHT, RADIUS, TRANSLATE); _visual2D3D.Visual = grd3D; _visual2D3D.Transform = new TranslateTransform3D(0, 0, _cameraLength * .3); _viewport.IsHitTestVisible = true; _viewport.Children.Add(_visual2D3D); #endregion #region Detail Visual _detailVisual = new ModelVisual3D(); _detailVisual.Content = GetBlankModel(); Transform3DGroup transform = new Transform3DGroup(); _detailRotationInitial = new QuaternionRotation3D(); transform.Children.Add(new RotateTransform3D(_detailRotationInitial)); _detailRotationAnimate = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 0); transform.Children.Add(new RotateTransform3D(_detailRotationAnimate)); _detailTranslate = new TranslateTransform3D(0, 0, 0); // this one is so the model can be centered on zero transform.Children.Add(_detailTranslate); _detailScale = new ScaleTransform3D(1, 1, 1); transform.Children.Add(_detailScale); transform.Children.Add(new TranslateTransform3D(_cameraLength * .1, 0, 0)); // this one is so the visual is shifted into the final place on screen _detailVisual.Transform = transform; _viewport.Children.Add(_detailVisual); UpdateDetailVisual(); #endregion _detailAnimate = AnimateRotation.Create_Constant(_detailRotationAnimate, 30); chkIs3D.IsChecked = _is3DPanel; _isInitialized = true; Update2D3DPanels(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "BackdropPanel", MessageBoxButton.OK, MessageBoxImage.Error); } }
void ConfigureModel(Viewport2DVisual3D model, int index) { if (index == selectedIndex) { var transformGroup = GetSelectedModelTransform(index); model.Transform = transformGroup; } else { var transformGroup = GetModelTransforms(index); model.Transform = transformGroup; } var elem = model.Visual as UIElement; elem.BeginAnimation(UIElement.OpacityProperty, null); elem.Opacity = this.GetElementOpacity(index);// this.AutoAdjustOpacity ? this.GetElementOpacity(index) : 1.0; }
Viewport2DVisual3D GetNextModel(Viewport2DVisual3D current) { if (!_models.Contains(current)) throw new ArgumentException("current"); // Wrap to the start of the list if necessary. int idx = _models.IndexOf(current) + 1; if (idx == _models.Count) idx = 0; return _models[idx]; }
Viewport2DVisual3D GetPreviousModel(Viewport2DVisual3D current) { if (!_models.Contains(current)) throw new ArgumentException("current"); // Wrap to the end of the list if necessary. int idx = _models.IndexOf(current) - 1; if (idx == -1) idx = _models.Count - 1; return _models[idx]; }
public void BuildScene(Viewport2DVisual3D frontModel) { int oldViewRangeStartIndex = ViewRangeStartIndex; int oldViewingRangeStopIndex = ViewingRangeStopIndex; //Determine what items to build SetViewRangeStartStopIndex(); //Ensure these values are within a range that wont error the GetRange() method call ViewRangeStartIndex = ViewRangeStartIndex < 0 ? 0 : ViewRangeStartIndex; ViewingRangeStopIndex = ViewingRangeStopIndex > _models.Count - 1 ? _models.Count : ViewingRangeStopIndex; if (isMoveingPeiceIntoView == false) { if (oldViewRangeStartIndex != ViewRangeStartIndex || oldViewingRangeStopIndex != ViewingRangeStopIndex || needsUpdate == true) { methodFireCount++; // Debug.WriteLine("Build Method Internal Has Fired :" + methodFireCount); _viewport.RemoveAllModels(); var current = frontModel; int modelCounter = ViewRangeStartIndex; // Debug.WriteLine("Build Start and End Index :" + ViewRangeStartIndex + " " + (ViewingRangeStopIndex - ViewRangeStartIndex)); foreach (var item in _models.GetRange(ViewRangeStartIndex, (ViewingRangeStopIndex) - ViewRangeStartIndex)) { this.ConfigureModel(item, modelCounter); _viewport.AddToBack(item); modelCounter++; } needsUpdate = false; } } }
private void BuildUp() { var geometry = new MeshGeometry3D(); double x = CubeLength / 2; double y = CubeHeight / 2; double z = CubeWidth / 2; geometry.Positions = new Point3DCollection((new Point3D[] { new Point3D(-x, y,z), new Point3D(x,y,z), new Point3D(x,y,-z), new Point3D(-x,y,-z) })); //三角形构造,影响呈现的正反面 geometry.TriangleIndices = new Int32Collection(new int[] { 0, 1, 2, 2, 3, 0 }); //纹理 geometry.TextureCoordinates = new PointCollection(new Point[] { new Point(0, 1), new Point(1, 1), new Point(1, 0), new Point(0, 0) }); if (upViewPort != null) { upViewPort.Geometry = geometry; return; } //顶层 upViewPort = new Viewport2DVisual3D(); upViewPort.Geometry = geometry; var grid = new Grid(); if (UpContent != null) upViewPort.Visual = UpContent; else { grid.Children.Add(new TextBlock() { Text = "顶部", Background = Brushes.Blue }); upViewPort.Visual = grid; } upViewPort.Material = material; Children.Add(upViewPort); }