//Called on teleport, so that the noise levels for the listener can be recalculated void updateListener() { currTrees.Clear(); foreach (Transform child in transform) { noiseParameters vehicleParams = child.GetComponent <noiseParameters>(); if (vehicleParams == null) { continue; } ; //Skip this object if parameters are missing NoiseSource noise = new NoiseSource(); noise.debug = debugMode; noise.origin = child.position; noise.controller = this; noise.node = new TreeNode <NoiseSource>(noise); noise.fireAt(listener, maximumDistance); if (reflections) { noise.reflectToward(listener, maximumDistance); } //Transform tree into audio generateAudio(child.gameObject, noise, vehicleParams); } }
void Awake() { m_laserBeam = GetComponent <LineRenderer>(); m_collider = GetComponent <BoxCollider>(); noiseSource = GetComponent <NoiseSource>(); m_wantedLevel = GameObject.FindObjectOfType <WantedLevel>(); }
public void TestCreateNoiseSourceWhisWall() { var width = 3; var height = 3; GameSetter.SetMapAndFillWithDecors(width, height, new List <Tuple <Point, IDecor> > { Tuple.Create(new Point(1, 1), (IDecor) new Wall()), Tuple.Create(new Point(1, 0), (IDecor) new Wall()) }); var map = GetMap(width, height); var sourse = new NoiseSource(NoiseType.GuardVoice, 1, 4, new Point(2, 1), ""); Dijkstra.DijkstraTraversal(map, sourse, (noises, noise) => { noises.Add(noise); }); var mapAnswer = GetMap(width, height); ChangeMap(mapAnswer, Tuple.Create(new Point(0, 0), new Noise(sourse, 1)), Tuple.Create(new Point(0, 1), new Noise(sourse, 2)), Tuple.Create(new Point(0, 2), new Noise(sourse, 2)), Tuple.Create(new Point(1, 2), new Noise(sourse, 3)), Tuple.Create(new Point(2, 0), new Noise(sourse, 3)), Tuple.Create(new Point(2, 1), new Noise(sourse, 4)), Tuple.Create(new Point(2, 2), new Noise(sourse, 3))); CheckMap(map, mapAnswer); }
public void TestCreateTwoNoiseSource() { var width = 2; var height = 2; GameSetter.SetMapAndFillWithDecors(width, height, new List <Tuple <Point, IDecor> >()); var map = GetMap(width, height); var sourse1 = new NoiseSource(NoiseType.GuardVoice, 1, 2, new Point(1, 1), ""); var sourse2 = new NoiseSource(NoiseType.GuardVoice, 1, 2, new Point(0, 0), ""); Dijkstra.DijkstraTraversal(map, sourse1, (noises, noise) => { noises.Add(noise); }); Dijkstra.DijkstraTraversal(map, sourse2, (noises, noise) => { noises.Add(noise); }); var mapAnswer = GetMap(width, height); ChangeMap(mapAnswer, Tuple.Create(new Point(0, 0), new Noise(sourse1, 1)), Tuple.Create(new Point(0, 1), new Noise(sourse1, 1)), Tuple.Create(new Point(1, 0), new Noise(sourse1, 1)), Tuple.Create(new Point(1, 1), new Noise(sourse1, 2))); ChangeMap(mapAnswer, Tuple.Create(new Point(0, 0), new Noise(sourse2, 2)), Tuple.Create(new Point(0, 1), new Noise(sourse2, 1)), Tuple.Create(new Point(1, 0), new Noise(sourse2, 1)), Tuple.Create(new Point(1, 1), new Noise(sourse2, 1))); CheckMap(map, mapAnswer); }
//Diffractions private void scanCast(GameObject listener, Vector3 target, Vector3 direction, float maxDist, string dirName, Collider lastHit) { for (int i = 0; i < controller.collisionChecks; i++) { RaycastHit hit; //Move target up in each step target += direction * controller.rayResolution; //Once it hits only air, continue if (!Physics.Linecast(origin, target, out hit, controller.reflectionMask)) { //Stop if the sound has travelled too far maxDist = maxDist - Vector3.Distance(origin, target); if (maxDist < 0) { if (debug) { Debug.DrawLine(origin, target, Color.yellow, controller.period); } return; } //Stop, if new source is farther from the target than the current one if (Vector3.Distance(listener.transform.position, origin) < Vector3.Distance(listener.transform.position, target)) { if (debug) { Debug.DrawLine(origin, target, Color.red, controller.period); } return; } NoiseSource nextSegment = new NoiseSource(); nextSegment.origin = target; nextSegment.debug = debug; nextSegment.node = node.AddChild(nextSegment); nextSegment.controller = controller; nextSegment.fireAt(listener, maxDist, dirName, lastHit); nextSegment.hitObject = hit.collider; //Save type of diffraction if (dirName == "left" || dirName == "right") { nextSegment.type = HitType.DIFFRACTION_H; } else { nextSegment.type = HitType.DIFFRACTION_V; } if (debug) { Debug.DrawLine(origin, nextSegment.origin, Color.blue, controller.period); } return; } lastHit = hit.collider; //For corner case, where we immediately hit another collider } //If it didn't manage to get away from the obstacle, draw red line //Debug.DrawLine(origin, listener.transform.position, Color.red, controller.period); }
public IEnumerator TerrainNoiseOutputsNotFlat(NoiseSource noiseSource) { TerrainNoise terrainNoise = makeTerrainNoise(noiseSource); float[,] heightMap = new float[3, 3]; terrainNoise.FillHeightMapNoise(0, 0, heightMap); Assert.AreNotEqual(heightMap[0, 0], heightMap[0, 2]); Assert.AreNotEqual(heightMap[0, 0], heightMap[2, 0]); yield return(null); }
private void Start() { m_audioSource = gameObject.GetComponent <AudioSource>(); m_Animator = this.GetComponent <Animator>(); m_NoiseSource = GetComponent <NoiseSource>(); if (FootSoundPairs.Length > 0) { CurrentFootLeft = FootSoundPairs[0].FootLeft; CurrentFootRight = FootSoundPairs[0].FootRight; } }
private void OnValidate() { // falls die komponenten nicht zugewiesen sind, tu dies automatisch rigidbody = this.GetComponent <Rigidbody>(); collider = this.GetComponent <Collider>(); noiseSource = this.GetComponent <NoiseSource>(); hingePosition = new Vector3(transform.position.x, 0, transform.position.z); rigidbody.isKinematic = true; this.enabled = false; }
public void TestRemoveNoiseSourceWithLowIntensity() { var width = 5; var height = 5; GameSetter.SetMapAndFillWithDecors(width, height, new List <Tuple <Point, IDecor> >()); var map = GetMap(width, height); var sourse = new NoiseSource(NoiseType.GuardVoice, 1, 2, new Point(2, 2), ""); Dijkstra.DijkstraTraversal(map, sourse, (noises, noise) => { noises.Add(noise); }); Dijkstra.DijkstraTraversal(map, sourse, (noises, noise) => { noises.Remove(noise); }); var mapAnswer = GetMap(width, height); CheckMap(map, mapAnswer); }
private static async Task NewTerrain(int seed) { var sw = Stopwatch.StartNew(); var size = 1024 * 2; var offsetX = size / 2; var offsetY = size / 2; var scale = 5d; var initialFrequency = 0.5d; var octaves = 6; var octaveOffsetScale = 100000; var amplitudePerOctave = 1.5d; var freqPerOctave = 0.5d; var data = NoiseSource.OpenSimplex2DOctaves(seed, size, offsetX, offsetY, scale, initialFrequency, octaves, octaveOffsetScale, amplitudePerOctave, freqPerOctave); data.Add((i, val) => { var x = (double)i % size / size; var y = (double)i / size / size; var d = Math.Max(Math.Abs(x * 2 - 1), Math.Abs(y * 2 - 1)); var f = NoiseSource.FalloffFunc(d, 1d, 5d); return(f); }); var minHeight = data.Min(); var maxHeight = data.Max(); var dataScaled = data.Select((i, val) => (byte)((val / maxHeight) * 255)); sw.Stop(); Console.WriteLine("In " + sw.ElapsedMilliseconds + "ms"); using (var fs = File.OpenWrite("./images/image" + seed + ".bmp")) using (var image = Image.LoadPixelData( dataScaled.AsPixelData((i, b) => new Bgra32(b < 255 / 2 ? b : (byte)0, b < 255 / 2 ? b : (byte)0, b)), size, size)) { image.SaveAsBmp(fs); await fs.FlushAsync(); fs.Close(); } }
public static TerrainNoise makeTerrainNoise(NoiseSource noiseSource) { GameObject gameObject = new GameObject(); UnityNoiseBase unityNoise = noiseSource(gameObject); TerrainNoise terrainNoise = gameObject.AddComponent <TerrainNoise>(); AnimationCurve animationCurve = new AnimationCurve() { keys = new Keyframe[] { new Keyframe(0, 0), new Keyframe(1, 1) } }; terrainNoise.HeightNoise = unityNoise; terrainNoise.DetailNoise = unityNoise; terrainNoise.HeightAdjustCurve = animationCurve; //unityNoise.Awake(); terrainNoise.Start(); return(terrainNoise); }
public List <ImageSource> calculateNoise(NoiseController controller, NoiseSource src, noiseParameters vehicleParams) { currController = controller; currSource = src; currVehicle = vehicleParams; images = new List <ImageSource>(); List <propagationStep> start = new List <propagationStep>(); //turn propagation paths into image sources //Recursively work through to the leafs, then add to images foreach (TreeNode <NoiseSource> node in src.node.Children) { pathFromTo(src.node, src.node, node, 0, 0, start); } //After this loop, the list of images is populated return(images); }
private void generateAudio(GameObject noiseObject, NoiseSource noiseTree, noiseParameters vehicleParams) { //Save tree currTrees.Add(noiseTree); //Convert tree of noise propagation paths into list of image sources for audio playback NMBP2008 noiseModel = new NMBP2008(); List <ImageSource> audioSources = noiseModel.calculateNoise(this, noiseTree, vehicleParams); //Check if sound is already running NoisePlayer nP = noiseObject.GetComponent <NoisePlayer>(); if (nP == null) { nP = noiseObject.AddComponent <NoisePlayer>(); } nP.play(audioSources, audioSourceObject); }
//Iterates through the tree of noise paths, and at every point draws debug lines to all children private void drawNoise(NoiseSource src) { foreach (TreeNode <NoiseSource> child in src.node.Children) { Vector3 start = src.origin; Vector3 end = child.Value.origin; float width = lineWidth; Color lineColor = Color.cyan; lineColor.a = 0.3f; //If world is miniaturized, change width and color so that they fit but are still visible. if (downscaled) { width = width * scaleFactor * 2; lineColor.a = 0.6f; } //Diffraction if (child.Value.type == NoiseSource.HitType.DIFFRACTION_V || child.Value.type == NoiseSource.HitType.DIFFRACTION_H) { //lineDrawer.DrawLineInGameView(start, end, width, Color.blue, lineContainer); lineDrawer.DrawLineInGameView(start, end, width, lineColor, lineContainer); } //Reflection if (child.Value.type == NoiseSource.HitType.REFLECTION) { //lineDrawer.DrawLineInGameView(start, end, width, Color.yellow, lineContainer); lineDrawer.DrawLineInGameView(start, end, width, lineColor, lineContainer); } //Final hit if (child.Value.type == NoiseSource.HitType.DIRECT) { //lineDrawer.DrawLineInGameView(start, end + Vector3.down, width, Color.green, lineContainer); lineDrawer.DrawLineInGameView(start, end + Vector3.down, width, lineColor, lineContainer); } } }
public static void DijkstraTraversal(Map <HashSet <Noise> > noises, NoiseSource source, Action <HashSet <Noise>, Noise> changer) { var visited = new HashSet <Point>(); var potentialTransition = new Dictionary <Point, Noise> { { source.Position, new Noise(source, source.MaxIntensity) } }; while (true) { if (potentialTransition.Count == 0) { return; } var nextPoint = GetLowestCostPoint(potentialTransition); visited.Add(nextPoint.Item1); changer(noises[nextPoint.Item1.X, nextPoint.Item1.Y], nextPoint.Item2); potentialTransition.Remove(nextPoint.Item1); UpdateNeighboringPoint(nextPoint, potentialTransition, visited, noises); } }
public void fireAt(GameObject listener, float maxDist, string direction = "", Collider lastHit = null) { RaycastHit hit; if (Physics.Linecast(origin, listener.transform.position, out hit, controller.reflectionMask)) { //If full path is wanted, reset direction after each building if (controller.fullPath && hit.collider != lastHit) { direction = ""; } lastHit = hit.collider; //Push target in a centimeter, so that collisions work Vector3 target = hit.point - (hit.normal * 0.01f); //Build coordinate system for impact point, use up as reference Vector3 side; Vector3 up; if (hit.normal == Vector3.up) { //Regain direction by turning one of up's orthogonal axes to face the listener up = (listener.transform.position - hit.point); up.y = 0; up.Normalize(); side = Vector3.Cross(hit.normal, up).normalized; } else { side = Vector3.Cross(hit.normal, Vector3.up).normalized; up = Vector3.Cross(side, hit.normal).normalized; } if (debug) { Debug.DrawLine(hit.point, hit.point + hit.normal, Color.magenta, controller.period); } if (debug) { Debug.DrawLine(hit.point, hit.point + side, Color.magenta, controller.period); } if (debug) { Debug.DrawLine(hit.point, hit.point + up, Color.magenta, controller.period); } //If no direction given, check all four orthgonal vectors if (direction == "") { if (controller.sidewaysDiffraction) { scanCast(listener, target, Quaternion.AngleAxis(90, up) * hit.normal, maxDist, "right", lastHit); scanCast(listener, target, Quaternion.AngleAxis(-90, up) * hit.normal, maxDist, "left", lastHit); } scanCast(listener, target, Quaternion.AngleAxis(90, side) * hit.normal, maxDist, "up", lastHit); if (controller.downwardDiffraction) { scanCast(listener, target, Quaternion.AngleAxis(-90, side) * hit.normal, maxDist, "down", lastHit); } } else if (direction == "right" && controller.sidewaysDiffraction) { scanCast(listener, target, Quaternion.AngleAxis(90, up) * hit.normal, maxDist, "right", lastHit); } else if (direction == "left" && controller.sidewaysDiffraction) { scanCast(listener, target, Quaternion.AngleAxis(-90, up) * hit.normal, maxDist, "left", lastHit); } else if (direction == "up") { scanCast(listener, target, Quaternion.AngleAxis(90, side) * hit.normal, maxDist, "up", lastHit); } else if (direction == "down" && controller.downwardDiffraction) { scanCast(listener, target, Quaternion.AngleAxis(-90, side) * hit.normal, maxDist, "down", lastHit); } //If no path reached the listener, remove from noise tree if (node.Children.Count == 0) { node.RemoveSelf(); } } else { if (Vector3.Distance(listener.transform.position, origin) > maxDist) { if (debug) { Debug.DrawLine(origin, listener.transform.position, Color.yellow, 0.1f); } node.RemoveSelf(); } else { //Hit! if (debug) { Debug.DrawLine(origin, listener.transform.position, Color.green, 0.1f); } NoiseSource finalSegment = new NoiseSource(); finalSegment.origin = listener.transform.position; finalSegment.debug = debug; finalSegment.node = node.AddChild(finalSegment); finalSegment.controller = controller; finalSegment.type = HitType.DIRECT; finalSegment.hitObject = null; } } }
Color calculateNoiseLevelColor(GameObject dataPoint) { List <float> pathSoundLevels = new List <float>(); foreach (Transform child in transform) { noiseParameters vehicleParams = child.GetComponent <noiseParameters>(); if (vehicleParams == null) { return(Color.white); } ; //Skip this object if parameters are missing NoiseSource noise = new NoiseSource(); noise.debug = false; noise.origin = child.position; noise.controller = this; noise.node = new TreeNode <NoiseSource>(noise); noise.fireAt(dataPoint, maximumDistance); if (reflections) { noise.reflectToward(dataPoint, maximumDistance); } NMBP2008 noiseModel = new NMBP2008(); List <ImageSource> images = noiseModel.calculateNoise(this, noise, vehicleParams); foreach (ImageSource img in images) { pathSoundLevels.Add(aWeighting(img)); } } if (pathSoundLevels.Count == 0) { return(Color.white); } //Long term sound level float finalSoundLevel = 0; foreach (float dezibel in pathSoundLevels) { finalSoundLevel = finalSoundLevel + Mathf.Pow(10.0f, (dezibel / 10)); } finalSoundLevel = 10.0f * Mathf.Log10(finalSoundLevel); //Map value to something between 0 and 1, then map to color //Same mapping as in NoisePlayer.cs //float value = Mathf.Pow(10f, finalSoundLevel / 20f) * 0.00002f / 2f; //float minHue = 60f / 360; //corresponds to green //float maxHue = 1f / 360; //corresponds to red //float hue = value * maxHue + (1 - value) * minHue; //return Color.HSVToRGB(hue, 1, 0.7f); //Debug.Log("Soundlevel: " + finalSoundLevel + " Value: " + value + " Hue: " + hue); //Map to different danger levels if (finalSoundLevel < 65) { return(Color.green); } else if (finalSoundLevel < 80) { return(Color.yellow); } else { return(Color.red); } }
//Reflections public void reflectToward(GameObject listener, float maxDistance) { RaycastHit hit; Vector3 directionRight = listener.transform.position - origin; Vector3 directionLeft = listener.transform.position - origin; //We always need to stay on the plane between source and receiver. //But in order for that plane to have the correct "roll" we need another reference vector //This is the up vector. To make this work in all 3D configurations, //we need to "pitch" the Up vector back until it is orthogonal to our direction vector Vector3 axis; if (!directionRight.Equals(Vector3.up)) { axis = Vector3.Cross(directionRight, Vector3.up); // This gives us a sideways vector axis = Vector3.Cross(directionRight, axis).normalized; //This gives us the new upwards vector } else { //If the direction is directly up, just choose a direction axis = Vector3.right; } Quaternion rightStep = Quaternion.AngleAxis(1 / controller.angleSteps, axis); Quaternion leftStep = Quaternion.AngleAxis(-1 / controller.angleSteps, axis); for (int i = 0; i < controller.reflectionAngle * controller.angleSteps; i++) { directionRight = rightStep * directionRight; //Debug.DrawLine(origin, origin+directionRight, Color.red, controller.period); if (Physics.Raycast(origin, directionRight, out hit, controller.maximumDistance, controller.reflectionMask)) { if (debug) { Debug.DrawLine(origin, hit.point, Color.cyan, controller.period); } Vector3 reflectionPoint = hit.point + (hit.normal * 0.01f); //Reflection angle check if (Mathf.Abs(Vector3.SignedAngle(hit.normal, hit.point - origin, axis) + Vector3.SignedAngle(hit.normal, hit.point - listener.transform.position, axis)) > controller.specularTolerance) { if (debug) { Debug.DrawLine(origin, reflectionPoint, Color.cyan, controller.period); Debug.DrawLine(reflectionPoint, listener.transform.position, Color.cyan, controller.period); } } else { NoiseSource nextSegment = new NoiseSource(); nextSegment.origin = reflectionPoint; nextSegment.debug = debug; nextSegment.node = node.AddChild(nextSegment); nextSegment.controller = controller; nextSegment.type = HitType.REFLECTION; nextSegment.hitObject = hit.collider; nextSegment.fireAt(listener, maxDistance - Vector3.Distance(origin, hit.point), "right", hit.collider); } } directionLeft = leftStep * directionLeft; //Debug.DrawLine(origin, origin + directionLeft, Color.red, controller.period); if (Physics.Raycast(origin, directionLeft, out hit, controller.maximumDistance, controller.reflectionMask)) { if (debug) { Debug.DrawLine(origin, hit.point, Color.cyan, controller.period); } Vector3 reflectionPoint = hit.point + (hit.normal * 0.01f); //Reflection angle check if (Mathf.Abs(Vector3.SignedAngle(hit.normal, hit.point - origin, axis) + Vector3.SignedAngle(hit.normal, hit.point - listener.transform.position, axis)) > controller.specularTolerance) { if (debug) { Debug.DrawLine(origin, reflectionPoint, Color.cyan, controller.period); Debug.DrawLine(reflectionPoint, listener.transform.position, Color.cyan, controller.period); } } else { NoiseSource nextSegment = new NoiseSource(); nextSegment.origin = reflectionPoint; nextSegment.debug = debug; nextSegment.node = node.AddChild(nextSegment); nextSegment.controller = controller; nextSegment.type = HitType.REFLECTION; nextSegment.hitObject = hit.collider; nextSegment.fireAt(listener, maxDistance - Vector3.Distance(origin, hit.point), "left", hit.collider); } } } }
public static void RemoveNoiseSource(NoiseSource source) { NoiseController.RemoveSourceNoises(source); }
// Use this for initialization void Awake() { m_noiseSource = GetComponent <NoiseSource>(); }
public IEnumerator NoiseOutputsConnect(NoiseSource noiseSource) { // NOTE: Unity heightmaps are y,x indexed, even though it is inconsistent with everything else. TerrainNoise terrainNoise = makeTerrainNoise(noiseSource); float[,] middleMap = new float[3, 3]; float[,] rightMap = new float[3, 3]; float[,] upMap = new float[3, 3]; float[,] leftMap = new float[3, 3]; float[,] downMap = new float[3, 3]; terrainNoise.FillHeightMapNoise(0, 0, middleMap); terrainNoise.FillHeightMapNoise(2, 0, rightMap); terrainNoise.FillHeightMapNoise(0, 2, upMap); terrainNoise.FillHeightMapNoise(-2, 0, leftMap); terrainNoise.FillHeightMapNoise(0, -2, downMap); foreach (KeyValuePair <string, float[, ]> pair in new Dictionary <string, float[, ]>() { { "rightMap", rightMap }, { "upMap", upMap }, { "leftMap", leftMap }, { "downMap", downMap } }) { for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { for (int x2 = 0; x2 < 3; x2++) { for (int y2 = 0; y2 < 3; y2++) { if (middleMap[y, x] == pair.Value[y, x]) { Debug.Log($"MiddleMap coordinates {y},{x} matches {pair.Key} {y2},{x2}"); } } } } } Debug.Log(pair.Key); } Assert.AreEqual(middleMap[0, 2], rightMap[0, 0]); Assert.AreEqual(middleMap[1, 2], rightMap[1, 0]); Assert.AreEqual(middleMap[2, 2], rightMap[2, 0]); Assert.AreEqual(middleMap[2, 0], upMap[0, 0]); Assert.AreEqual(middleMap[2, 1], upMap[0, 1]); Assert.AreEqual(middleMap[2, 2], upMap[0, 2]); Assert.AreEqual(middleMap[0, 0], leftMap[0, 2]); Assert.AreEqual(middleMap[1, 0], leftMap[1, 2]); Assert.AreEqual(middleMap[2, 0], leftMap[2, 2]); Assert.AreEqual(middleMap[0, 0], downMap[2, 0]); Assert.AreEqual(middleMap[0, 1], downMap[2, 1]); Assert.AreEqual(middleMap[0, 2], downMap[2, 2]); yield return(null); }
// Generate noise map //mapSizeSqrt, mapSizeSqrt, seed, side, offset, octaves, persistence, lacunarity, noiseSource public static float[,] GenerateNoiseMap(int seed, Vector3 offset, GPUNoiseGenerator.NoiseData noise, float scale, NoiseSource source, int?meshGridSize = null, float zoom = 1, int performanceTestLoops = 1, float radius = 100) { int mapSizeSqrt = (int)noise.resolution; float[,] noiseMap = new float[mapSizeSqrt, mapSizeSqrt]; System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); for (int performanceLoopIndex = 0; performanceLoopIndex < performanceTestLoops; ++performanceLoopIndex) { switch (source) { case NoiseSource.Unity: #region [ - Unity Noise - ] Vector2 chunkOffset = offset; //GenerateFalloffMap(ref falloffMap, mapChunkSize); /* Generate Height Map * (mapSide tarkottaa yhen spherical cuben reunan HeightMapin kokoa) * [5] * [4] * [1][2][3] * [0] */ // Laskee sphericalCuben valitun lähtöpisteen for (int i = 0, len = int.Parse(((int)noise.side).ToString()); i <= len; ++i) { switch (i) { case 0: chunkOffset.x += mapSizeSqrt; break; case 1: chunkOffset.x -= mapSizeSqrt; chunkOffset.y += mapSizeSqrt; break; case 2: chunkOffset.x += mapSizeSqrt; break; case 3: chunkOffset.x += mapSizeSqrt; break; case 4: chunkOffset.x -= mapSizeSqrt; chunkOffset.y += mapSizeSqrt; break; case 5: chunkOffset.y += mapSizeSqrt; break; } } // Laskee quartereitten (..quartereitten (..quartereitten (..jne))) lähtöpisteen int quarterSize = mapSizeSqrt; for (int i = 0, len = noise.quarter.Length; i < len; ++i) { //quarterSize /= 2; // quarterin leveys\korkeus scale *= 2; switch (noise.quarter[i]) { case '0': // vasenala // -> piste ei liiku minnekkään Debug.Log("scale: " + scale + ", quarter size: " + quarterSize + ", side:" + noise.quarter[i] + ", offset: " + chunkOffset.x + " | " + chunkOffset.y); break; case '1': // oikeeala chunkOffset.x += quarterSize / scale; Debug.Log("scale: " + scale + ", quarter size: " + quarterSize + ", side:" + noise.quarter[i] + ", offset: " + chunkOffset.x + " | " + chunkOffset.y); break; case '2': // vasenylä chunkOffset.y += quarterSize / scale; Debug.Log("scale: " + scale + ", quarter size: " + quarterSize + ", side:" + noise.quarter[i] + ", offset: " + chunkOffset.x + " | " + chunkOffset.y); break; case '3': // oikeeylä chunkOffset.x += quarterSize / scale; chunkOffset.y += quarterSize / scale; Debug.Log("scale: " + scale + ", quarter size: " + quarterSize + ", side:" + noise.quarter[i] + ", offset: " + chunkOffset.x + " | " + chunkOffset.y); break; } } Vector2[] octaveOffset = new Vector2[noise.octaves]; maxPossibleHeight = 0; noise.amplitude = 1; noise.frequency = 1; NormalizeMode normalizeMode = NormalizeMode.Global; System.Random prng = new System.Random(seed); Vector2 randomOffsetFromSeed = new Vector2(prng.Next(-100000, 100000) - chunkOffset.x, prng.Next(-100000, 100000) - chunkOffset.y); for (i = 0; i < noise.octaves; ++i) { octaveOffset[i] = randomOffsetFromSeed; maxPossibleHeight += noise.amplitude; noise.amplitude *= noise.persistence; } if (scale <= 0) { scale = 0.0001f; } maxLocalNoiseHeight = float.MinValue; minLocalNoiseHeight = float.MaxValue; halfWidth = mapSizeSqrt / 2f; halfHeight = mapSizeSqrt / 2f; for (y = 0; y < mapSizeSqrt; ++y) { for (x = 0; x < mapSizeSqrt; ++x) { noise.amplitude = 1; noise.frequency = 1; noiseHeight = 0; for (i = 0; i < noise.octaves; ++i) // Oktaavien teko kuluttaa sikana eli tarkkana { sampleX = (x - mapSizeSqrt) / scale * noise.frequency + octaveOffset[i].x * noise.frequency; sampleY = (y - mapSizeSqrt) / scale * noise.frequency + octaveOffset[i].y * noise.frequency; perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1; // tää on raskas, * 2 - 1 tekee sen että se menee [-1, 1]) noiseHeight += perlinValue * noise.amplitude; //Debug.Log("X: " + x + ", Y: " + y + " | " + perlinValue + " | " + amplitude); noise.amplitude *= noise.persistence; noise.frequency *= noise.lacunarity; } if (noiseHeight > maxLocalNoiseHeight) { maxLocalNoiseHeight = noiseHeight; } else if (noiseHeight < minLocalNoiseHeight) { minLocalNoiseHeight = noiseHeight; } noiseMap[x, y] = noiseHeight; //Debug.Log("X: " + x + ", Y: " + y + " | " + noiseMap[x, y]); //noiseMap[x, y] = Mathf.InverseLerp(minLocalNoiseHeight, maxLocalNoiseHeight, noiseMap[x, y]); } } for (int y = 0; y < mapSizeSqrt; ++y) { for (int x = 0; x < mapSizeSqrt; ++x) { if (normalizeMode == NormalizeMode.Local) { noiseMap[x, y] = Mathf.InverseLerp(minLocalNoiseHeight, maxLocalNoiseHeight, noiseMap[x, y]); } else { float normalizedHeight = (noiseMap[x, y] + 1) / (maxPossibleHeight / 0.9f); noiseMap[x, y] = Mathf.Clamp(normalizedHeight, 0, int.MaxValue); } } } #endregion break; case NoiseSource.LibNoise: #region [ - LibNoise - ] Perlin perlinNoise = new Perlin { Quality = QualityMode.Medium, OctaveCount = noise.octaves, Lacunarity = noise.lacunarity, Seed = seed, Persistence = noise.persistence, Frequency = noise.frequency }; LibNoise.Unity.ModuleBase moduleBase; moduleBase = perlinNoise; Noise2D noise2D = new LibNoise.Unity.Noise2D((int)noise.resolution, (int)noise.resolution, moduleBase); //noise.GeneratePlanar((double)offset.x, (double)(offset.x + mapWidth), (double)(offset.y + mapHeight), (double)offset.y); noise2D.GeneratePlanar((int)noise.resolution, 0, (int)noise.resolution, 0); noiseMap = noise2D.m_data; #endregion break; case NoiseSource.GPU_2DFloatArray: #region [ - GPU 2D Float Array - ] noiseMap = GPUNoiseGenerator.GenerateNoiseArray(seed, noise, radius, meshGridSize, offset, zoom); #endregion break; case NoiseSource.GPU_RenderTextureTo2DFloatArray: #region [ - GPU Render Texture to 2D Float Array - ] noiseMap = GPUNoiseGenerator.GenerateNoiseArrayFromRenderTexture(seed, noise); #endregion break; default: return(null); } } st.Stop(); if (performanceTestLoops > 1) { Debug.Log(string.Format("Generated noise with {0} {1} times and it took {2} ms to complete.", source.ToString(), performanceTestLoops, st.ElapsedMilliseconds)); } return(noiseMap); }
private void Update() { var currentTime = Time.time; //set behavior state if (_noiseSourceToInvestigate && Vector3.SqrMagnitude(noiseSourceToInvestigateTransform.position - transform.position) < 1f) { _hasReachedNoiseSource = true; _noiseSourceToInvestigate = null; //TODO do a 360 } noiseSourceToInvestigateTransform.SetPositionAndRotation(_noiseSourceToInvestigateVector, Quaternion.identity); if (!awareOfPlayer) { StopAttackPlayer(); } if (awareOfPlayer) { AttackPlayer(); } else if (_noiseSourceToInvestigate) { InvestigateNoise(); if (!_isDead && _hasReachedNoiseSource) { Patrol(); } } if (health <= 0) { Kill(); } if (currentTime > _timeToStopStun) { isStunned = false; } if (!_isDead) { aiPath.enabled = !isStunned; } // enemy listens to noises and picks the loudest one accounting for distance falloff (inverse square) foreach (var noiseSource in _noiseSources) { var sqrDist = Vector3.SqrMagnitude(transform.position - noiseSource.transform.position); if ((noiseSource.noiseLevel * hearing / sqrDist) > 1f) { if (_noiseSourceToInvestigate) { var noiseSourceToInvestigateVolume = _noiseSourceToInvestigate.noiseLevel / Vector3.SqrMagnitude(transform.position - _noiseSourceToInvestigate.transform.position); if (noiseSource.noiseLevel / sqrDist > noiseSourceToInvestigateVolume) { _noiseSourceToInvestigate = noiseSource; _hasReachedNoiseSource = false; } } else { _noiseSourceToInvestigate = noiseSource; _hasReachedNoiseSource = false; } _noiseSourceToInvestigateVector = _noiseSourceToInvestigate.transform.position; } } //set animator parameters and facing if (aiPath.velocity.sqrMagnitude > 0.001f) { animator.SetBool(IsMoving, true); facing.x = aiPath.velocity.normalized.x; facing.y = aiPath.velocity.normalized.y; } else { animator.SetBool(IsMoving, false); } animator.SetFloat(Horizontal, facing.x); animator.SetFloat(Vertical, facing.y); //set field of view position and rotation fieldOfView.SetOrigin(transform.position); fieldOfView.SetAimDirection(new Vector3(facing.x, facing.y, 0)); //correct field of view game object position; fieldOfView.transform.position = Vector3.zero; FindPlayer(); //calculate awareness if (seesPlayer && !isStunned) { awareness += Time.deltaTime; } else if (currentTime > _stopAwareTime) { awareness -= Time.deltaTime; awareOfPlayer = false; } if (awareness > maxAwareness) { awareness = maxAwareness; _stopAwareTime = currentTime + awareDuration; awareOfPlayer = true; } if (awareness < 0) { awareness = 0; } //set awareness bar color awarenessBar.color = awareOfPlayer ? awareOfPlayerColor : awarenessBarColor; if (isStunned) { awarenessBar.color = stunnedColor; } //set awareness bar if (awareness > 0 && health > 0) { awarenessBar.enabled = true; var percentage = awareness / maxAwareness; var t = awarenessBar.transform; var scale = t.localScale; t.localScale = new Vector3(16f * percentage, scale.y, scale.z); var pos = t.position; t.position = new Vector3(-0.25f * percentage + transform.position.x, pos.y, pos.z); } }
public static void AddNoiseSourse(NoiseSource source) { NoiseController.AddNoiseSource(source); }