void insertPoint() { for (int i = pointCnt; i > 0; i--) points[i] = points[i - 1]; points[0] = new Point(transform); pointCnt++; }
/// <summary> /// 조절점 추가 /// </summary> /// <param name="timeRatio"></param> /// <param name="value"></param> public void AddPoint(float timeRatio, float value) { var newp = new Point { timeRatio = timeRatio, value = value }; int datacount = m_data.Count; if (datacount == 0) // 케이스 1 - 데이터가 없는 경우 바로 추가 { m_data.Add(newp); } else { // 데이터가 하나 이상일 경우엔 인덱스를 직접 구한다 var count = m_data.Count; bool inserted = false; for (int i = 0; i < count; i++) { if (m_data[i].timeRatio > timeRatio) // timeRatio가 더 큰 점을 찾는다면 바로 그 앞에 insert한다 { m_data.Insert(i, newp); inserted = true; } } if (!inserted) // 위 루프에서 점을 추가하지 못한 경우 맨 마지막에 추가 { m_data.Add(newp); } } }
/** * A display object rig to access pan, rotation and zoom actions. * @param viewport the starting viewable rectangle including position * @param startPosition Point reprsenting the position that the camera will return to on reset * @param easingPan The value used to determine how much the camera should move each step towards its target in X and Y. * @param easingZoom The value used to determine how much the camera should move each step towards its target for scale. * @param easingRotate The value used to determine how much the camera should move each step towards its target for rotation. * @param boundingRect A Rectangle that constrains the movement of the camera */ public CameraSprite(Rectangle viewport, Point startPosition=null, float easingPan=1f, float easingZoom=1f, float easingRotate=1, Rectangle boundingRect=null, Juggler juggler=null) { _juggler = juggler; _harness=new Harness(); // The harness is a container to manage rotation, scale and shaking without modifying the pivot and other properties of the main camera. _world=new World(this); _viewport=viewport; this.startPosition=startPosition; _easingPan=easingPan; _easingZoom=easingZoom; _easingRotate=easingRotate; if (boundingRect != null) { this.boundingRect=boundingRect; } else { this.boundingRect=NO_BOUNDS.toRectangle(); } _harness.center=new Point(_viewport.x + _viewport.width / 2, _viewport.y + _viewport.height / 2); base.addChildAt(_harness, 0); _harness.addChild(_world); }
// Use this for initialization void Start () { Texture2D imgTexture = Resources.Load ("lena") as Texture2D; Mat img1Mat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC3); Utils.texture2DToMat (imgTexture, img1Mat); Debug.Log ("img1Mat dst ToString " + img1Mat.ToString ()); Mat img2Mat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC3); Utils.texture2DToMat (imgTexture, img2Mat); Debug.Log ("img2Mat dst ToString " + img2Mat.ToString ()); float angle = UnityEngine.Random.Range (0, 360), scale = 1.0f; Point center = new Point (img2Mat.cols () * 0.5f, img2Mat.rows () * 0.5f); Mat affine_matrix = Imgproc.getRotationMatrix2D (center, angle, scale); Imgproc.warpAffine (img1Mat, img2Mat, affine_matrix, img2Mat.size ()); FeatureDetector detector = FeatureDetector.create (FeatureDetector.ORB); DescriptorExtractor extractor = DescriptorExtractor.create (DescriptorExtractor.ORB); MatOfKeyPoint keypoints1 = new MatOfKeyPoint (); Mat descriptors1 = new Mat (); detector.detect (img1Mat, keypoints1); extractor.compute (img1Mat, keypoints1, descriptors1); MatOfKeyPoint keypoints2 = new MatOfKeyPoint (); Mat descriptors2 = new Mat (); detector.detect (img2Mat, keypoints2); extractor.compute (img2Mat, keypoints2, descriptors2); DescriptorMatcher matcher = DescriptorMatcher.create (DescriptorMatcher.BRUTEFORCE_HAMMINGLUT); MatOfDMatch matches = new MatOfDMatch (); matcher.match (descriptors1, descriptors2, matches); Mat resultImg = new Mat (); Features2d.drawMatches (img1Mat, keypoints1, img2Mat, keypoints2, matches, resultImg); Texture2D texture = new Texture2D (resultImg.cols (), resultImg.rows (), TextureFormat.RGBA32, false); Utils.matToTexture2D (resultImg, texture); gameObject.GetComponent<Renderer> ().material.mainTexture = texture; }
private void floodFill(Point startPoint, Biome parentBiome) { Queue<Point> queue = new Queue<Point>(); HashSet<Point> queuedPoints = new HashSet<Point>(); queue.Enqueue(startPoint); queuedPoints.Add(startPoint); Point currentPoint; BiomeMapPixel currentPixel; while (queue.Count > 0) { currentPoint = queue.Dequeue(); currentPixel = m_data[currentPoint.y, currentPoint.x]; if (currentPixel.GetPrimaryBiome() == parentBiome.Type) { currentPixel.ParentBiome = parentBiome; ++parentBiome.Size; foreach (Point neighbour in currentPoint.Neighbours) { if (neighbour.IsInBounds(0, 0, Size, Size) && GetPixelAtPoint(neighbour).ParentBiome == null && !queuedPoints.Contains(neighbour)) { queue.Enqueue(neighbour); queuedPoints.Add(neighbour); } } } } }
public virtual void Brush(Point pixel, Sprite image, Blend.BlendFunction blend) { pixel = pixel - new Point(image.pivot); Point grid, offset; Cells.Coords(pixel, out grid, out offset); var gw = Mathf.CeilToInt((image.rect.width + offset.x) / Cells.CellWidth); var gh = Mathf.CeilToInt((image.rect.height + offset.y) / Cells.CellHeight); for (int y = 0; y < gh; ++y) { for (int x = 0; x < gw; ++x) { IDrawing drawing; Point cell = new Point(grid.x + x, grid.y + y); if (Cells.GetDefault(cell, out drawing, NewCell)) { var point = new Point(x * Cells.CellWidth, y * Cells.CellHeight); drawing.Brush(offset - point + image.pivot, image, blend); Changed.Set(cell, true); } } } }
public SweepEvent(Point p, bool isLeft, PolygonType polygonType, SweepEvent otherSweepEvent, EdgeType edgeType) { this.p = p; this.isLeft = isLeft; this.polygonType = polygonType; this.otherSE = otherSweepEvent; this.edgeType = edgeType; }
public virtual void Brush(Point offset, Sprite image, Blend.BlendFunction blend) { var rtrans = transform as RectTransform; Drawing.Brush(offset - (Point) rtrans.localPosition, image, blend); }
public void SetToPoint(Point p) { currentPoint = p; if (currentPoint != null) transform.localPosition = currentPoint.transform.localPosition; else transform.localPosition = new Vector3(-10000, -10000, 0); }
public TiledDrawing(Point cellsize, SparseGrid<IDrawing>.Constructor newCell = null) { Cells = new SparseGrid<IDrawing>(cellsize.x, cellsize.y); Changed = new SparseGrid<bool>(cellsize.x, cellsize.y); NewCell = newCell ?? NullCell; }
public static Rectangle inflatePoint(Rectangle rect, Point pt) { rect.x -= pt.x; rect.y -= pt.y; rect.width += pt.x * 2; rect.height += pt.y * 2; return rect; }
public void SetTransparency(bool b) { if (_sprite != null) _sprite.color = new Color(_sprite.color.r, _sprite.color.g, _sprite.color.b, (b) ? 0.5f : 1f); if (currentPoint != null) currentPoint.isPugalka = !b; if (b) currentPoint = null; }
public bool Sample(Point pixel, out Color color) { pixel = pixel.Offset(Sprite.textureRect.position); Assert.IsTrue(Sprite.textureRect.Contains((Vector2) pixel), "Fill out of bounds!"); color = Sprite.texture.GetPixel(pixel.x, pixel.y); return true; }
public Room (int maxRoomSize, int minRoomSize, int cellSizeX, int cellSizeY, Point pos, int maxDistortion = 0) { connectedRooms = new List<int> (); this.pos = pos; this.width = Random.Range (minRoomSize, maxRoomSize); this.height = Random.Range (minRoomSize, maxRoomSize); map = new int[cellSizeX, cellSizeY]; //Центрирование int minBorderX = (cellSizeX - width) / 2; int maxBorderX = width + minBorderX; int minBorderY = (cellSizeY - height) / 2; int maxBorderY = height + minBorderY; //Генерация прямоугольника комнаты for (int i = 0; i != cellSizeX; i++) { for (int j = 0; j != cellSizeY; j++) { if ((j > minBorderY && j < maxBorderY) && (i > minBorderX && i < maxBorderX)) map [i, j] = 1; else map [i, j] = 0; } } //Генерация ответвлений for (int i = 0; i != maxDistortion; i++) { //Стартовая координата int startX = Random.Range (minBorderX, maxBorderX); int startY = Random.Range (minBorderY, maxBorderY); int stopX = Random.Range (maxBorderX, maxRoomSize); int stopY = Random.Range (maxBorderY, maxRoomSize); for (int x = startX; x != stopX; x++) { for (int y = startY; y != stopY; y++) { map [x, y] = 1; } } } for (int i = 0; i != cellSizeX; i++) { for (int j = 0; j != cellSizeY; j++) { if (map [i, j] == 1 && ( map [i + 1, j] == 0 || //map [i - 1, j] == 0 || map [i, j + 1] == 0 )) //map [i, j - 1] == 0)) map [i, j] = 3; } } }
public virtual void Fill(Point pixel, Color color) { IDrawing drawing; Point grid, offset; Cells.Coords(pixel, out grid, out offset); if (Cells.Get(grid, out drawing)) { drawing.Fill(offset, color); Changed.Set(grid, true); } }
public void Reset() { gameObject.SetActive(true); transform.right = Vector3.right; _lastSearchPathTime = -100f; delay = 2f; _currentPoint = null; _currentPath = new List<Point>(); if (listStartPoints.Count > 0) { _currentPoint = listStartPoints[Random.Range(0, listStartPoints.Count)]; transform.localPosition = _currentPoint.transform.localPosition; } _isActive = true; }
// Use this for initialization void Start() { //srcMat Texture2D srcTexture = Resources.Load ("matchshapes") as Texture2D; Mat srcMat = new Mat (srcTexture.height, srcTexture.width, CvType.CV_8UC1); Utils.texture2DToMat (srcTexture, srcMat); Debug.Log ("srcMat.ToString() " + srcMat.ToString ()); Imgproc.threshold (srcMat, srcMat, 127, 255, Imgproc.THRESH_BINARY); //dstMat Texture2D dstTexture = Resources.Load ("matchshapes") as Texture2D; Mat dstMat = new Mat (dstTexture.height, dstTexture.width, CvType.CV_8UC3); Utils.texture2DToMat (dstTexture, dstMat); Debug.Log ("dstMat.ToString() " + dstMat.ToString ()); List<MatOfPoint> srcContours = new List<MatOfPoint> (); Mat srcHierarchy = new Mat (); /// Find srcContours Imgproc.findContours (srcMat, srcContours, srcHierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_NONE); Debug.Log ("srcContours.Count " + srcContours.Count); for (int i=0; i<srcContours.Count; i++) { Imgproc.drawContours (dstMat, srcContours, i, new Scalar (255, 0, 0), 2, 8, srcHierarchy, 0, new Point ()); } for (int i=0; i<srcContours.Count; i++) { double returnVal = Imgproc.matchShapes (srcContours [1], srcContours [i], Imgproc.CV_CONTOURS_MATCH_I1, 0); Debug.Log ("returnVal " + i + " " + returnVal); Point point = new Point (); float[] radius = new float[1]; Imgproc.minEnclosingCircle (new MatOfPoint2f (srcContours [i].toArray ()), point, radius); Debug.Log ("point.ToString() " + point.ToString ()); Debug.Log ("radius.ToString() " + radius [0]); Imgproc.circle (dstMat, point, 5, new Scalar (0, 0, 255), -1); Imgproc.putText (dstMat, " " + returnVal, point, Core.FONT_HERSHEY_SIMPLEX, 0.4, new Scalar (0, 255, 0), 1, Imgproc.LINE_AA, false); } Texture2D texture = new Texture2D (dstMat.cols (), dstMat.rows (), TextureFormat.RGBA32, false); Utils.matToTexture2D (dstMat, texture); gameObject.GetComponent<Renderer> ().material.mainTexture = texture; }
private Dictionary<Vector3, Dictionary<Color, Dictionary<Vector3, Point>>> mesh_ = null; // = new Dictionary<Vector3, Point>(); #endregion Fields #region Methods public static Dictionary<Vector3, Dictionary<Color, Dictionary<Vector3, Point>>> Draw2Mesh(VoxelDrawData draw) { Dictionary<Vector3, Dictionary<Color, Dictionary<Vector3, Point>>> mesh = new Dictionary<Vector3, Dictionary<Color, Dictionary<Vector3, Point>>>();// = new Dictionary<Vector3, Point>(); List<VoxelDrawData.Vertice> vex = draw.vertices; for (int i = 0; i < vex.Count; ++i) { VoxelDrawData.Vertice v = vex[i]; if (!mesh.ContainsKey (v.normal)) { mesh [v.normal] = new Dictionary<Color, Dictionary<Vector3, Point>> (); } if (!mesh [v.normal].ContainsKey (v.color)) { mesh [v.normal] [v.color] = new Dictionary<Vector3, Point> (); } Point point = new Point (); point.vertice = v; mesh [v.normal] [v.color][v.position] = point; } List<int> trx = draw.triangles; for (int i = 0; i < trx.Count; i += 3) { VoxelDrawData.Vertice a = vex [trx [i]]; VoxelDrawData.Vertice b = vex [trx [i+1]]; VoxelDrawData.Vertice c = vex [trx [i+2]]; Dictionary<Vector3, Point> m = mesh [a.normal] [a.color]; Point A = m [a.position]; Point B = m [b.position]; Point C = m [c.position]; A.link.Add (B); A.link.Add (C); B.link.Add (A); B.link.Add (C); C.link.Add (A); C.link.Add (B); } return mesh; }
public virtual bool Sample(Point pixel, out Color color) { IDrawing drawing; Point grid, offset; Cells.Coords(pixel, out grid, out offset); if (Cells.Get(grid, out drawing)) { return drawing.Sample(offset, out color); } else { color = Color.black; return false; } }
public BiomeMap(TerrainGenerator newTerrainData) { m_terrainData = newTerrainData; m_data = new BiomeMapPixel[Size, Size]; //Set biome weights for all pixels Point position; for (int x = 0; x < Size; ++x) { for (int y = 0; y < Size; ++y) { position = new Point(x, y); float heightAboveSeaLevel = m_terrainData.GetHeightAboveSeaLevelAt(position); float latitude = Mathf.Clamp(position.y / (float)m_terrainData.Heightmap.size, 0f, 1f); float precipitation = m_terrainData.Rainmap.GetValueAt(position); m_data[y, x] = new BiomeMapPixel(latitude, heightAboveSeaLevel, precipitation); } } //Iterate through all pixels, setting their parent Biome for (int x = 0; x < Size; ++x) { for (int y = 0; y < Size; ++y) { //Ignore pixels that have already had their parent biome set. if (m_data[y, x].ParentBiome != null) { continue; } //Generate a new Biome object from the primary biome type of this pixel. Biome biome = new Biome(m_data[y, x].GetPrimaryBiome()); //Flood fill the map with that biome. floodFill(new Point(x, y), biome); //Generate a name for that biome, now that it knows how big it is. biome.GenerateName(); } } }
// Use this for initialization void Start() { Texture2D srcTexture = Resources.Load ("template") as Texture2D; Texture2D dstTexture = Resources.Load ("lena") as Texture2D; Mat src = new Mat (srcTexture.height, srcTexture.width, CvType.CV_8UC3); Mat dst = new Mat (dstTexture.height, dstTexture.width, CvType.CV_8UC3); Utils.texture2DToMat (srcTexture, src); Utils.texture2DToMat (dstTexture, dst); Mat mask = new Mat (src.rows (), src.cols (), CvType.CV_8UC1, new Scalar (255)); Mat result = new Mat (); Point point = new Point (315, 450); Photo.seamlessClone (src, dst, mask, point, result, Photo.NORMAL_CLONE); Debug.Log ("result ToString " + result.ToString ()); Texture2D texture = new Texture2D (result.cols (), result.rows (), TextureFormat.RGBA32, false); Utils.matToTexture2D (result, texture); gameObject.GetComponent<Renderer> ().material.mainTexture = texture; }
public static Brush Line(Point start, Point end, Color color, int thickness) { var tl = new Point(Mathf.Min(start.x, end.x), Mathf.Min(start.y, end.y)); int left = Mathf.FloorToInt(thickness / 2f); Point size = (end - start).Size + new Point(thickness, thickness); var pivot = tl * -1 + Vector2.one * left; var anchor = new Vector2(pivot.x / (float) size.x, pivot.y / (float) size.y); var rect = new Rect(0, 0, size.x, size.y); Texture2D image = BlankTexture.New(size.x, size.y, Color.clear); Brush brush = new Brush(Sprite.Create(image, rect, anchor, 1)); brush.sprite.name = "Line (Brush)"; using (Brush circle = Circle(thickness, color)) { Bresenham.PlotFunction plot = delegate (int x, int y) { Apply(circle, new Point(x, y), brush, Point.Zero, Blend.Alpha); return true; }; Bresenham.Line(start.x, start.y, end.x, end.y, plot); } brush.sprite.texture.Apply(); return brush; }
public static void GetTriangle(Point point, List<Triangle> trx) { //a[normal][color][position] HashSet<Point> link = new HashSet<Point>(); foreach (Point o in point.link) { link.Add (o); } foreach (Point o in point.link) { foreach(Point l in o.link){ if (link.Contains (l)) { trx.Add(new Triangle (point, o, l)); } } link.Remove(o); o.link.Remove (point); } point.link.Clear (); }
private void NewPosition(Point p) { Point prewPoint = _currentPoint; _currentPoint = p; _targetPoint = null; // Проверка на победу или проигрыш if (_currentPoint.isMousetrap) { MiniGame23_Manager.instance.KilledRat(this); return; } else if (_currentPoint.isCable) { MiniGame23_Manager.instance.EatCable(_currentPoint); return; } else if (_currentPoint.isPugalka) { if (_currentPath != null) _currentPath.Clear(); _targetPoint = prewPoint; return; } // Если нет пути, пытаемся найти if ((_currentPath == null || _currentPath.Count == 0) && Time.timeSinceLevelLoad - _lastSearchPathTime > 3f) { _lastSearchPathTime = Time.timeSinceLevelLoad; if (_currentPath == null) _currentPath = new List<Point>(); else _currentPath.Clear(); List<Point> l = new List<Point>(); if (!MiniGame23_Manager.instance.FindShorterPath(ref _currentPath, ref l, null, _currentPoint, pointFinish)) _currentPath.Clear(); //string s = ""; //foreach (Point pp in _currentPath) // s += pp.ToString() + " "; //Debug.Log(s); } // Если нашли, выбираем новую точку, к которой будем двигаться if (_currentPath != null && _currentPath.Count > 0) { if (_currentPath.Contains(_currentPoint)) { int index = _currentPath.IndexOf(_currentPoint); if (_currentPath.Count > index + 1) { _targetPoint = _currentPath[index + 1]; //Debug.Log("true"); } } else _currentPath.Clear(); } if (_targetPoint == null || _targetPoint.isPugalka) { if (_currentPath != null) _currentPath.Clear(); // Выбираем точки из текущей позиции, к которым можем двигаться и двигаемся к случайной List<Point> list = new List<Point>(); foreach (Point point in _currentPoint.listPoints) if (!point.isPugalka && point != _currentPoint) list.Add(point); //Debug.Log(list.Count); if (list.Count > 1) if (list.Contains(prewPoint)) list.Remove(prewPoint); if (list.Count > 0) _targetPoint = list[Random.Range(0, list.Count)]; else _targetPoint = null; } }
/// <summary> /// Converts the screen point. /// </summary> /// <returns>The screen point.</returns> /// <param name="screenPoint">Screen point.</param> /// <param name="quad">Quad.</param> /// <param name="cam">Cam.</param> static Point convertScreenPoint(Point screenPoint, GameObject quad, Camera cam) { Vector2 tl; Vector2 tr; Vector2 br; Vector2 bl; tl = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x - quad.transform.localScale.x / 2, quad.transform.localPosition.y + quad.transform.localScale.y / 2, quad.transform.localPosition.z)); tr = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x + quad.transform.localScale.x / 2, quad.transform.localPosition.y + quad.transform.localScale.y / 2, quad.transform.localPosition.z)); br = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x + quad.transform.localScale.x / 2, quad.transform.localPosition.y - quad.transform.localScale.y / 2, quad.transform.localPosition.z)); bl = cam.WorldToScreenPoint (new Vector3 (quad.transform.localPosition.x - quad.transform.localScale.x / 2, quad.transform.localPosition.y - quad.transform.localScale.y / 2, quad.transform.localPosition.z)); Mat srcRectMat = new Mat (4, 1, CvType.CV_32FC2); Mat dstRectMat = new Mat (4, 1, CvType.CV_32FC2); srcRectMat.put (0, 0, tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y); dstRectMat.put (0, 0, 0.0, 0.0, quad.transform.localScale.x, 0.0, quad.transform.localScale.x, quad.transform.localScale.y, 0.0, quad.transform.localScale.y); Mat perspectiveTransform = Imgproc.getPerspectiveTransform (srcRectMat, dstRectMat); // Debug.Log ("srcRectMat " + srcRectMat.dump ()); // Debug.Log ("dstRectMat " + dstRectMat.dump ()); // Debug.Log ("perspectiveTransform " + perspectiveTransform.dump ()); MatOfPoint2f srcPointMat = new MatOfPoint2f (screenPoint); MatOfPoint2f dstPointMat = new MatOfPoint2f (); Core.perspectiveTransform (srcPointMat, dstPointMat, perspectiveTransform); // Debug.Log ("srcPointMat " + srcPointMat.dump ()); // Debug.Log ("dstPointMat " + dstPointMat.dump ()); return dstPointMat.toArray () [0]; }
public void Fill(Point pixel, Color color) { Sprite.texture.FloodFillAreaNPO2(pixel.x, pixel.y, color, Sprite.textureRect); }
public void Brush(Point offset, Sprite image, Blend.BlendFunction blend) { PixelDraw.Brush.Apply(image, offset, Sprite, new Point(0, 0), blend); }
void Update() { if (emit && emitTime > 0) { emitTime -= Time.deltaTime; if (emitTime < 0.001) emit = false; } if (!emit && points.Count == 0 && autoDestruct) { Destroy(o); } // early out if there is no camera if (!Camera.main) return; bool re = false; // if we have moved enough, create a new vertex and make sure we rebuild the mesh float theDistance = (_lastPosition - transform.position).magnitude; if (emit) { if (theDistance > minVertexDistance) { bool make = false; if (points.Count < 3) { make = true; } else { Vector3 l1 = ((Point)points[points.Count - 2]).Position - ((Point)points[points.Count - 3]).Position; Vector3 l2 = ((Point)points[points.Count - 1]).Position - ((Point)points[points.Count - 2]).Position; if (Vector3.Angle(l1, l2) > maxAngle || theDistance > maxVertexDistance) make = true; } if (make) { Point p = new Point(); p.Position = transform.position; p.TimeCreated = Time.time; points.Add(p); _lastPosition = transform.position; } else { ((Point)points[points.Count - 1]).Position = transform.position; ((Point)points[points.Count - 1]).TimeCreated = Time.time; } } else if (points.Count > 0) { ((Point)points[points.Count - 1]).Position = transform.position; ((Point)points[points.Count - 1]).TimeCreated = Time.time; } } if (!emit && _lastFrameEmit && points.Count > 0) ((Point)points[points.Count - 1]).LineBreak = true; _lastFrameEmit = emit; // approximate if we should rebuild the mesh or not if (points.Count > 1) { Vector3 cur1 = Camera.main.WorldToScreenPoint(((Point)points[0]).Position); _lastCameraPosition1.z = 0; Vector3 cur2 = Camera.main.WorldToScreenPoint(((Point)points[points.Count - 1]).Position); _lastCameraPosition2.z = 0; float distance = (_lastCameraPosition1 - cur1).magnitude; distance += (_lastCameraPosition2 - cur2).magnitude; if (distance > movePixelsForRebuild || Time.time - _lastRebuildTime > maxRebuildTime) { re = true; _lastCameraPosition1 = cur1; _lastCameraPosition2 = cur2; } } else { re = true; } if (re) { _lastRebuildTime = Time.time; ArrayList remove = new ArrayList(); int i = 0; foreach (Point p in points) { // cull old points first if (Time.time - p.TimeCreated > lifeTime) remove.Add(p); i++; } foreach (Point p in remove) points.Remove(p); remove.Clear(); if (points.Count > 1) { Vector3[] newVertices = new Vector3[points.Count * 2]; Vector2[] newUV = new Vector2[points.Count * 2]; int[] newTriangles = new int[(points.Count - 1) * 6]; Color[] newColors = new Color[points.Count * 2]; i = 0; float curDistance = 0.00f; foreach (Point p in points) { float time = (Time.time - p.TimeCreated) / lifeTime; Color color = Color.Lerp(Color.white, Color.clear, time); if (Colors != null && Colors.Length > 0) { float colorTime = time * (Colors.Length - 1); float min = Mathf.Floor(colorTime); float max = Mathf.Clamp(Mathf.Ceil(colorTime), 1, Colors.Length - 1); float lerp = Mathf.InverseLerp(min, max, colorTime); if (min >= Colors.Length) min = Colors.Length - 1; if (min < 0) min = 0; if (max >= Colors.Length) max = Colors.Length - 1; if (max < 0) max = 0; color = Color.Lerp(Colors[(int)min], Colors[(int)max], lerp); } float size = 1f; if (Sizes != null && Sizes.Length > 0) { float sizeTime = time * (Sizes.Length - 1); float min = Mathf.Floor(sizeTime); float max = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, Sizes.Length - 1); float lerp = Mathf.InverseLerp(min, max, sizeTime); if (min >= Sizes.Length) min = Sizes.Length - 1; if (min < 0) min = 0; if (max >= Sizes.Length) max = Sizes.Length - 1; if (max < 0) max = 0; size = Mathf.Lerp(Sizes[(int)min], Sizes[(int)max], lerp); } Vector3 perpendicular = Vector3.up;//Vector3.Cross(lineDirection, vectorToCamera).normalized; newVertices[i * 2] = p.Position + (perpendicular * (size * 0.5f)); newVertices[(i * 2) + 1] = p.Position + (-perpendicular * (size * 0.5f)); newColors[i * 2] = newColors[(i * 2) + 1] = color; newUV[i * 2] = new Vector2(curDistance * UvLengthScale, 0); newUV[(i * 2) + 1] = new Vector2(curDistance * UvLengthScale, 1); if (i > 0 && !((Point)points[i - 1]).LineBreak) { if (HigherQualityUVs) curDistance += (p.Position - ((Point)points[i - 1]).Position).magnitude; else curDistance += (p.Position - ((Point)points[i - 1]).Position).sqrMagnitude; newTriangles[(i - 1) * 6] = (i * 2) - 2; newTriangles[((i - 1) * 6) + 1] = (i * 2) - 1; newTriangles[((i - 1) * 6) + 2] = i * 2; newTriangles[((i - 1) * 6) + 3] = (i * 2) + 1; newTriangles[((i - 1) * 6) + 4] = i * 2; newTriangles[((i - 1) * 6) + 5] = (i * 2) - 1; } i++; } if (o != null) { Mesh mesh = (o.GetComponent<MeshFilter>() as MeshFilter).mesh; mesh.Clear(); mesh.vertices = newVertices; mesh.colors = newColors; mesh.uv = newUV; mesh.triangles = newTriangles; } } } }
/// <summary> /// Init this instance. /// </summary> private IEnumerator init () { if (webCamTexture != null) { webCamTexture.Stop (); initDone = false; rgbaMat.Dispose (); } // Checks how many and which cameras are available on the device for (int cameraIndex = 0; cameraIndex < WebCamTexture.devices.Length; cameraIndex++) { if (WebCamTexture.devices [cameraIndex].isFrontFacing == isFrontFacing) { Debug.Log (cameraIndex + " name " + WebCamTexture.devices [cameraIndex].name + " isFrontFacing " + WebCamTexture.devices [cameraIndex].isFrontFacing); webCamDevice = WebCamTexture.devices [cameraIndex]; webCamTexture = new WebCamTexture (webCamDevice.name, width, height); break; } } if (webCamTexture == null) { webCamDevice = WebCamTexture.devices [0]; webCamTexture = new WebCamTexture (webCamDevice.name, width, height); } Debug.Log ("width " + webCamTexture.width + " height " + webCamTexture.height + " fps " + webCamTexture.requestedFPS); // Starts the camera webCamTexture.Play (); while (true) { //If you want to use webcamTexture.width and webcamTexture.height on iOS, you have to wait until webcamTexture.didUpdateThisFrame == 1, otherwise these two values will be equal to 16. (http://forum.unity3d.com/threads/webcamtexture-and-error-0x0502.123922/) #if UNITY_IOS && !UNITY_EDITOR && (UNITY_4_6_3 || UNITY_4_6_4 || UNITY_5_0_0 || UNITY_5_0_1) if (webCamTexture.width > 16 && webCamTexture.height > 16) { #else if (webCamTexture.didUpdateThisFrame) { #endif Debug.Log ("width " + webCamTexture.width + " height " + webCamTexture.height + " fps " + webCamTexture.requestedFPS); Debug.Log ("videoRotationAngle " + webCamTexture.videoRotationAngle + " videoVerticallyMirrored " + webCamTexture.videoVerticallyMirrored + " isFrongFacing " + webCamDevice.isFrontFacing); colors = new Color32[webCamTexture.width * webCamTexture.height]; rgbaMat = new Mat (webCamTexture.height, webCamTexture.width, CvType.CV_8UC4); texture = new Texture2D (webCamTexture.width, webCamTexture.height, TextureFormat.RGBA32, false); gameObject.transform.localEulerAngles = new Vector3 (0, 0, 0); // gameObject.transform.rotation = gameObject.transform.rotation * Quaternion.AngleAxis (webCamTexture.videoRotationAngle, Vector3.back); gameObject.transform.localScale = new Vector3 (webCamTexture.width, webCamTexture.height, 1); // bool videoVerticallyMirrored = webCamTexture.videoVerticallyMirrored; // float scaleX = 1; // float scaleY = videoVerticallyMirrored ? -1.0f : 1.0f; // gameObject.transform.localScale = new Vector3 (scaleX * gameObject.transform.localScale.x, scaleY * gameObject.transform.localScale.y, 1); gameObject.GetComponent<Renderer> ().material.mainTexture = texture; Camera.main.orthographicSize = webCamTexture.height / 2; //set cameraparam int max_d = Mathf.Max (rgbaMat.rows (), rgbaMat.cols ()); camMatrix = new Mat (3, 3, CvType.CV_64FC1); camMatrix.put (0, 0, max_d); camMatrix.put (0, 1, 0); camMatrix.put (0, 2, rgbaMat.cols () / 2.0f); camMatrix.put (1, 0, 0); camMatrix.put (1, 1, max_d); camMatrix.put (1, 2, rgbaMat.rows () / 2.0f); camMatrix.put (2, 0, 0); camMatrix.put (2, 1, 0); camMatrix.put (2, 2, 1.0f); Debug.Log ("camMatrix " + camMatrix.dump ()); distCoeffs = new MatOfDouble (0, 0, 0, 0); Debug.Log ("distCoeffs " + distCoeffs.dump ()); //calibration camera Size imageSize = new Size (rgbaMat.cols (), rgbaMat.rows ()); double apertureWidth = 0; double apertureHeight = 0; double[] fovx = new double[1]; double[] fovy = new double[1]; double[] focalLength = new double[1]; Point principalPoint = new Point (); double[] aspectratio = new double[1]; Calib3d.calibrationMatrixValues (camMatrix, imageSize, apertureWidth, apertureHeight, fovx, fovy, focalLength, principalPoint, aspectratio); Debug.Log ("imageSize " + imageSize.ToString ()); Debug.Log ("apertureWidth " + apertureWidth); Debug.Log ("apertureHeight " + apertureHeight); Debug.Log ("fovx " + fovx [0]); Debug.Log ("fovy " + fovy [0]); Debug.Log ("focalLength " + focalLength [0]); Debug.Log ("principalPoint " + principalPoint.ToString ()); Debug.Log ("aspectratio " + aspectratio [0]); //Adjust Unity Camera FOV for (int i = 0; i < ARCamera.Length; i++) { ARCamera [i].fieldOfView = (float)fovy [0]; } markerDetector = new MarkerDetector (camMatrix, distCoeffs); //Marker Coordinate Initial Matrix lookAtM = getLookAtMatrix (new Vector3 (0, 0, 0), new Vector3 (0, 0, 1), new Vector3 (0, -1, 0)); Debug.Log ("lookAt " + lookAtM.ToString ()); //OpenGL to Unity Coordinate System Convert Matrix //http://docs.unity3d.com/ScriptReference/Camera-worldToCameraMatrix.html that camera space matches OpenGL convention: camera's forward is the negative Z axis. This is different from Unity's convention, where forward is the positive Z axis. invertZM = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, new Vector3 (1, 1, -1)); Debug.Log ("invertZM " + invertZM.ToString ()); initDone = true; break; } else { yield return 0; } } } // Update is called once per frame void Update () { if (!initDone) return; #if UNITY_IOS && !UNITY_EDITOR && (UNITY_4_6_3 || UNITY_4_6_4 || UNITY_5_0_0 || UNITY_5_0_1) if (webCamTexture.width > 16 && webCamTexture.height > 16) { #else if (webCamTexture.didUpdateThisFrame) { #endif Utils.webCamTextureToMat (webCamTexture, rgbaMat, colors); //flip to correct direction. if (webCamTexture.videoVerticallyMirrored) { if (webCamDevice.isFrontFacing) { if (webCamTexture.videoRotationAngle == 0) { Core.flip (rgbaMat, rgbaMat, -1); } else if (webCamTexture.videoRotationAngle == 180) { Core.flip (rgbaMat, rgbaMat, 0); } } else { if (webCamTexture.videoRotationAngle == 0) { } else if (webCamTexture.videoRotationAngle == 180) { Core.flip (rgbaMat, rgbaMat, 1); } } } else { if (webCamDevice.isFrontFacing) { if (webCamTexture.videoRotationAngle == 0) { Core.flip (rgbaMat, rgbaMat, 1); } else if (webCamTexture.videoRotationAngle == 180) { Core.flip (rgbaMat, rgbaMat, 0); } } else { if (webCamTexture.videoRotationAngle == 0) { } else if (webCamTexture.videoRotationAngle == 180) { Core.flip (rgbaMat, rgbaMat, -1); } } } markerDetector.processFrame (rgbaMat, 1); //Debug.Log ("markerDetector.getTransformations ().Count " + markerDetector.getTransformations ().Count); for (int i = 0; i < ARCamera.Length; i++) { ARCamera [i].gameObject.SetActive (false); } int markerCount = markerDetector.getTransformations ().Count; for (int i = 0; i < markerCount; i++) { if (i > ARCamera.Length - 1) break; ARCamera [i].gameObject.SetActive (true); //Marker to Camera Coordinate System Convert Matrix transformationM = markerDetector.getTransformations () [i]; //Debug.Log ("transformationM " + transformationM.ToString ()); worldToCameraM = lookAtM * transformationM * invertZM; //Debug.Log ("worldToCameraM " + worldToCameraM.ToString ()); ARCamera [i].worldToCameraMatrix = worldToCameraM; } Utils.matToTexture2D (rgbaMat, texture, colors); gameObject.GetComponent<Renderer> ().material.mainTexture = texture; } } void OnDisable () { webCamTexture.Stop (); } /// <summary> /// Gets the look at matrix. /// </summary> /// <returns>The look at matrix.</returns> /// <param name="pos">Position.</param> /// <param name="target">Target.</param> /// <param name="up">Up.</param> private Matrix4x4 getLookAtMatrix (Vector3 pos, Vector3 target, Vector3 up) { Vector3 z = Vector3.Normalize (pos - target); Vector3 x = Vector3.Normalize (Vector3.Cross (up, z)); Vector3 y = Vector3.Normalize (Vector3.Cross (z, x)); Matrix4x4 result = new Matrix4x4 (); result.SetRow (0, new Vector4 (x.x, x.y, x.z, -(Vector3.Dot (pos, x)))); result.SetRow (1, new Vector4 (y.x, y.y, y.z, -(Vector3.Dot (pos, y)))); result.SetRow (2, new Vector4 (z.x, z.y, z.z, -(Vector3.Dot (pos, z)))); result.SetRow (3, new Vector4 (0, 0, 0, 1)); return result; } void OnGUI () { float screenScale = Screen.height / 240.0f; Matrix4x4 scaledMatrix = Matrix4x4.Scale (new Vector3 (screenScale, screenScale, screenScale)); GUI.matrix = scaledMatrix; GUILayout.BeginVertical (); if (GUILayout.Button ("back")) { Application.LoadLevel ("MarkerBasedARSample"); } if (GUILayout.Button ("change camera")) { isFrontFacing = !isFrontFacing; StartCoroutine (init ()); } GUILayout.EndVertical (); } }
public Triangle(Point a, Point b, Point c) { a_ = a; b_ = b; c_ = c; }