Procedural Planets

Integrated Sebastian Lague's Planet Generator
Created Tour function in SectorRenderer which makes the camera follow each terrestrial planet in turn
This commit is contained in:
Reinier Vens 2020-12-05 23:43:02 +00:00
commit 53a91351b7
332 changed files with 11904 additions and 78 deletions

View file

@ -0,0 +1,48 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ChanceTest : MonoBehaviour {
public Chance chance;
public int total;
void Update () {
if (Input.GetKeyDown (KeyCode.Space)) {
chance = new Chance (new System.Random ());
total++;
if (chance.Percent (10)) {
Debug.Log ("1");
}
if (chance.Percent (70)) {
Debug.Log ("7");
}
if (chance.Percent (20)) {
Debug.Log ("2");
}
}
}
}
public class Chance {
float value;
public Chance (System.Random prng) {
value = (float) prng.NextDouble ();
}
public Chance (PRNG prng) {
value = prng.Value ();
}
public bool Percent (float percent) {
if (value <= 0) {
return false;
}
float t = percent / 100f;
value -= t;
return value <= 0;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dbd90d6e181eb5145ad5cb26288bb585
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,176 @@
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
public static class ComputeHelper {
// Subscribe to this event to be notified when buffers created in edit mode should be released
// (i.e before script compilation occurs, and when exitting edit mode)
public static event System.Action shouldReleaseEditModeBuffers;
// Convenience method for dispatching a compute shader.
// It calculates the number of thread groups based on the number of iterations needed.
public static void Run (ComputeShader cs, int numIterationsX, int numIterationsY = 1, int numIterationsZ = 1, int kernelIndex = 0) {
Vector3Int threadGroupSizes = GetThreadGroupSizes (cs, kernelIndex);
int numGroupsX = Mathf.CeilToInt (numIterationsX / (float) threadGroupSizes.x);
int numGroupsY = Mathf.CeilToInt (numIterationsY / (float) threadGroupSizes.y);
int numGroupsZ = Mathf.CeilToInt (numIterationsZ / (float) threadGroupSizes.y);
cs.Dispatch (kernelIndex, numGroupsX, numGroupsY, numGroupsZ);
}
// Only run compute shaders if this is true
// This is only relevant for compute shaders that run outside of playmode
public static bool CanRunEditModeCompute {
get {
return CheckIfCanRunInEditMode ();
}
}
// Set all values from settings object on the shader. Note, variable names must be an exact match in the shader.
// Settings object can be any class/struct containing vectors/ints/floats/bools
public static void SetParams (System.Object settings, ComputeShader shader, string variableNamePrefix = "", string variableNameSuffix = "") {
var fields = settings.GetType ().GetFields ();
foreach (var field in fields) {
var fieldType = field.FieldType;
string shaderVariableName = variableNamePrefix + field.Name + variableNameSuffix;
if (fieldType == typeof (UnityEngine.Vector4) || fieldType == typeof (Vector3) || fieldType == typeof (Vector2)) {
shader.SetVector (shaderVariableName, (Vector4) field.GetValue (settings));
} else if (fieldType == typeof (int)) {
shader.SetInt (shaderVariableName, (int) field.GetValue (settings));
} else if (fieldType == typeof (float)) {
shader.SetFloat (shaderVariableName, (float) field.GetValue (settings));
} else if (fieldType == typeof (bool)) {
shader.SetBool (shaderVariableName, (bool) field.GetValue (settings));
} else {
Debug.Log ($"Type {fieldType} not implemented");
}
}
}
public static void CreateStructuredBuffer<T> (ref ComputeBuffer buffer, int count) {
int stride = System.Runtime.InteropServices.Marshal.SizeOf (typeof (T));
bool createNewBuffer = buffer == null || !buffer.IsValid () || buffer.count != count || buffer.stride != stride;
if (createNewBuffer) {
Release (buffer);
buffer = new ComputeBuffer (count, stride);
}
}
public static void CreateStructuredBuffer<T> (ref ComputeBuffer buffer, T[] data) {
CreateStructuredBuffer<T> (ref buffer, data.Length);
buffer.SetData (data);
}
// Test
public static ComputeBuffer CreateAndSetBuffer<T> (T[] data, ComputeShader cs, string nameID, int kernelIndex = 0) {
ComputeBuffer buffer = null;
CreateAndSetBuffer<T> (ref buffer, data, cs, nameID, kernelIndex);
return buffer;
}
public static void CreateAndSetBuffer<T> (ref ComputeBuffer buffer, T[] data, ComputeShader cs, string nameID, int kernelIndex = 0) {
int stride = System.Runtime.InteropServices.Marshal.SizeOf (typeof (T));
CreateStructuredBuffer<T> (ref buffer, data.Length);
buffer.SetData (data);
cs.SetBuffer (kernelIndex, nameID, buffer);
}
public static ComputeBuffer CreateAndSetBuffer<T> (int length, ComputeShader cs, string nameID, int kernelIndex = 0) {
ComputeBuffer buffer = null;
CreateAndSetBuffer<T> (ref buffer, length, cs, nameID, kernelIndex);
return buffer;
}
public static void CreateAndSetBuffer<T> (ref ComputeBuffer buffer, int length, ComputeShader cs, string nameID, int kernelIndex = 0) {
CreateStructuredBuffer<T> (ref buffer, length);
cs.SetBuffer (kernelIndex, nameID, buffer);
}
// Releases supplied buffer/s if not null
public static void Release (params ComputeBuffer[] buffers) {
for (int i = 0; i < buffers.Length; i++) {
if (buffers[i] != null) {
buffers[i].Release ();
}
}
}
public static Vector3Int GetThreadGroupSizes (ComputeShader compute, int kernelIndex = 0) {
uint x, y, z;
compute.GetKernelThreadGroupSizes (kernelIndex, out x, out y, out z);
return new Vector3Int ((int) x, (int) y, (int) z);
}
public static void CreateRenderTexture (ref RenderTexture texture, int size, FilterMode filterMode = FilterMode.Bilinear, GraphicsFormat format = GraphicsFormat.R16G16B16A16_SFloat) {
CreateRenderTexture (ref texture, size, size, filterMode, format);
}
public static void CreateRenderTexture (ref RenderTexture texture, int width, int height, FilterMode filterMode = FilterMode.Bilinear, GraphicsFormat format = GraphicsFormat.R16G16B16A16_SFloat) {
if (texture == null || !texture.IsCreated () || texture.width != width || texture.height != height || texture.graphicsFormat != format) {
if (texture != null) {
texture.Release ();
}
texture = new RenderTexture (width, height, 0);
texture.graphicsFormat = format;
texture.enableRandomWrite = true;
texture.autoGenerateMips = false;
texture.Create ();
}
texture.wrapMode = TextureWrapMode.Clamp;
texture.filterMode = filterMode;
}
// https://cmwdexint.com/2017/12/04/computeshader-setfloats/
public static float[] PackFloats (params float[] values) {
float[] packed = new float[values.Length * 4];
for (int i = 0; i < values.Length; i++) {
packed[i * 4] = values[i];
}
return values;
}
// Editor helpers:
#if UNITY_EDITOR
static UnityEditor.PlayModeStateChange playModeState;
static ComputeHelper () {
// Monitor play mode state
UnityEditor.EditorApplication.playModeStateChanged -= MonitorPlayModeState;
UnityEditor.EditorApplication.playModeStateChanged += MonitorPlayModeState;
// Monitor script compilation
UnityEditor.Compilation.CompilationPipeline.compilationStarted -= OnCompilationStarted;
UnityEditor.Compilation.CompilationPipeline.compilationStarted += OnCompilationStarted;
}
static void MonitorPlayModeState (UnityEditor.PlayModeStateChange state) {
playModeState = state;
if (state == UnityEditor.PlayModeStateChange.ExitingEditMode) {
if (shouldReleaseEditModeBuffers != null) {
shouldReleaseEditModeBuffers (); //
}
}
}
static void OnCompilationStarted (System.Object obj) {
if (shouldReleaseEditModeBuffers != null) {
shouldReleaseEditModeBuffers ();
}
}
#endif
static bool CheckIfCanRunInEditMode () {
bool isCompilingOrExitingEditMode = false;
#if UNITY_EDITOR
isCompilingOrExitingEditMode |= UnityEditor.EditorApplication.isCompiling;
isCompilingOrExitingEditMode |= playModeState == UnityEditor.PlayModeStateChange.ExitingEditMode;
#endif
bool canRun = !isCompilingOrExitingEditMode;
return canRun;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 711fda09f27fe41dfa8af54cab7ed80c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,116 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class MathUtility {
public static bool RaySphere (Vector3 centre, float radius, Vector3 rayOrigin, Vector3 rayDir, out Vector3 intersectionPoint) {
// See: http://viclw17.github.io/2018/07/16/raytracing-ray-sphere-intersection/
Vector3 offset = rayOrigin - centre;
float a = Vector3.Dot (rayDir, rayDir); // sqr ray length (in case of non-normalized rayDir)
float b = 2 * Vector3.Dot (offset, rayDir);
float c = Vector3.Dot (offset, offset) - radius * radius;
float discriminant = b * b - 4 * a * c;
// No intersections: discriminant < 0
// 1 intersection: discriminant == 0
// 2 intersections: discriminant > 0
if (discriminant >= 0) {
float t = (-b - Mathf.Sqrt (discriminant)) / (2 * a);
//float t2 = (-b + Mathf.Sqrt (discriminant)) / (2 * a); // The further away intersection point
// If t is negative, the intersection was in negative ray direction so ignore it
if (t >= 0) {
intersectionPoint = rayOrigin + rayDir * t;
return true;
}
}
intersectionPoint = Vector3.zero;
return false;
}
public static bool LineSegmentsIntersect (Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2) {
float d = (b2.x - b1.x) * (a1.y - a2.y) - (a1.x - a2.x) * (b2.y - b1.y);
if (d == 0)
return false;
float t = ((b1.y - b2.y) * (a1.x - b1.x) + (b2.x - b1.x) * (a1.y - b1.y)) / d;
float u = ((a1.y - a2.y) * (a1.x - b1.x) + (a2.x - a1.x) * (a1.y - b1.y)) / d;
return t >= 0 && t <= 1 && u >= 0 && u <= 1;
}
public static bool LinesIntersect (Vector2 a1, Vector2 a2, Vector2 a3, Vector2 a4) {
return (a1.x - a2.x) * (a3.y - a4.y) - (a1.y - a2.y) * (a3.x - a4.x) != 0;
}
public static Vector2 PointOfLineLineIntersection (Vector2 a1, Vector2 a2, Vector2 a3, Vector2 a4) {
float d = (a1.x - a2.x) * (a3.y - a4.y) - (a1.y - a2.y) * (a3.x - a4.x);
if (d == 0) {
Debug.LogError ("Lines are parallel, please check that this is not the case before calling line intersection method");
return Vector2.zero;
} else {
float n = (a1.x - a3.x) * (a3.y - a4.y) - (a1.y - a3.y) * (a3.x - a4.x);
float t = n / d;
return a1 + (a2 - a1) * t;
}
}
public static Vector2 ClosestPointOnLineSegment (Vector2 p, Vector2 a, Vector2 b) {
Vector2 aB = b - a;
Vector2 aP = p - a;
float sqrLenAB = aB.sqrMagnitude;
if (sqrLenAB == 0)
return a;
float t = Mathf.Clamp01 (Vector2.Dot (aP, aB) / sqrLenAB);
return a + aB * t;
}
public static Vector3 ClosestPointOnLineSegment (Vector3 p, Vector3 a, Vector3 b) {
Vector3 aB = b - a;
Vector3 aP = p - a;
float sqrLenAB = aB.sqrMagnitude;
if (sqrLenAB == 0)
return a;
float t = Mathf.Clamp01 (Vector3.Dot (aP, aB) / sqrLenAB);
return a + aB * t;
}
public static int SideOfLine (Vector2 a, Vector2 b, Vector2 c) {
return (int) Mathf.Sign ((c.x - a.x) * (-b.y + a.y) + (c.y - a.y) * (b.x - a.x));
}
/// returns the smallest angle between ABC. Never greater than 180
public static float MinAngle (Vector3 a, Vector3 b, Vector3 c) {
return Vector3.Angle ((a - b), (c - b));
}
public static bool PointInTriangle (Vector2 a, Vector2 b, Vector2 c, Vector2 p) {
float area = 0.5f * (-b.y * c.x + a.y * (-b.x + c.x) + a.x * (b.y - c.y) + b.x * c.y);
float s = 1 / (2 * area) * (a.y * c.x - a.x * c.y + (c.y - a.y) * p.x + (a.x - c.x) * p.y);
float t = 1 / (2 * area) * (a.x * b.y - a.y * b.x + (a.y - b.y) * p.x + (b.x - a.x) * p.y);
return s >= 0 && t >= 0 && (s + t) <= 1;
}
public static bool PointsAreClockwise (Vector2[] points) {
float signedArea = 0;
for (int i = 0; i < points.Length; i++) {
int nextIndex = (i + 1) % points.Length;
signedArea += (points[nextIndex].x - points[i].x) * (points[nextIndex].y + points[i].y);
}
return signedArea >= 0;
}
public static Vector2 V3ToXZ (Vector3 v3) {
return new Vector2 (v3.x, v3.z);
}
public static Vector3 V2ToXYZ (Vector2 v2, float yValue) {
return new Vector3 (v2.x, yValue, v2.y);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 69df6ef4fd0704bd9835a45dbb941451
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using UnityEngine;
public class PRNG {
public enum Weight { None, Lower, Upper, Centre, Ends }
System.Random prng;
int seed;
public int Seed {
get {
return seed;
}
}
public PRNG (int seed) {
this.seed = seed;
prng = new System.Random (this.seed);
}
public PRNG (string seed) {
this.seed = seed.GetHashCode ();
prng = new System.Random (this.seed);
}
public PRNG () {
prng = new System.Random ();
}
/// Returns a random integer value [min, max)
public int Range (int min, int max) {
return prng.Next (min, max);
}
/// Returns a random float value [min, max)
public float Range (float min, float max) {
return Mathf.Lerp (min, max, (float) prng.NextDouble ());
}
// Returns a vector4 where each component is a random number in range [min, max)
public Vector4 RangeVector4 (float minInclusive, float maxExclusive) {
Vector4 vector = Vector4.zero;
for (int i = 0; i < 4; i++) {
vector[i] = Range (minInclusive, maxExclusive);
}
return vector;
}
/// Random value [0, 1]
public float Value () {
// According to stackoverflow this should technically allow the random value to equal 1
const double maxExclusive = 1.0000000004656612875245796924106;
return (float) (prng.NextDouble () * maxExclusive);
}
/// Random value [0, 1]
/// Output is increasingly biased toward 1 as biasStrength goes from 0 to 1
public float ValueBiasUpper (float biasStrength) {
return 1 - ValueBiasLower (biasStrength);
}
/// Random value [0, 1]
/// Output is increasingly biased toward 0 as biasStrength goes from 0 to 1
public float ValueBiasLower (float biasStrength) {
float t = Value ();
// Avoid possible division by zero
if (biasStrength == 1) {
return 0;
}
// Remap strength for nicer input -> output relationship
float k = Mathf.Clamp01 (1 - biasStrength);
k = k * k * k - 1;
// Thanks to www.shadertoy.com/view/Xd2yRd
return Mathf.Clamp01 ((t + t * k) / (t * k + 1));
}
/// Random value [0, 1]
/// Output is increasingly biased toward the extremes (0 or 1) as biasStrength goes from 0 to 1
public float ValueBiasExtremes (float biasStrength) {
float t = ValueBiasLower (biasStrength);
return (Value () < 0.5f) ? t : 1 - t;
}
/// Random value [0, 1]
/// Output is increasingly biased toward 0.5 as biasStrength goes from 0 to 1
public float ValueBiasCentre (float biasStrength) {
float t = ValueBiasLower (biasStrength);
return 0.5f + t * 0.5f * Sign ();
}
// ---- Signed versions [-1, 1] ---
/// Random value [-1, 1]
public float SignedValue () {
return Value () * 2 - 1;
}
/// Random value [-1, 1]
/// Output is increasingly biased toward the extremes (-1 or 1) as biasStrength goes from 0 to 1
public float SignedValueBiasExtremes (float biasStrength) {
return ValueBiasExtremes (biasStrength) * 2 - 1;
}
/// Random value [-1, 1]
/// Output is increasingly biased toward 0 as biasStrength goes from 0 to 1
public float SignedValueBiasCentre (float biasStrength) {
return ValueBiasCentre (biasStrength) * 2 - 1;
}
// Returns a weighted value in range [min, max)
public float WeightedRange (float min, float max, Weight weight, int weightStrength = 4) {
float value01 = WeightedValue (weight, weightStrength);
return Mathf.Lerp (min, max, value01);
}
// Returns a weighted value in range [-1, 1)
public float WeightedSignedValue (Weight weight, int weightStrength = 4) {
return WeightedValue (weight, weightStrength) * 2 - 1;
}
// Returns a weighted value in range [0, 1)
public float WeightedValue (Weight weight, int weightStrength = 4) {
if (weight == Weight.None) {
return Value ();
}
float smallestValue = Value ();
for (int i = 0; i < weightStrength; i++) {
smallestValue = Mathf.Min (smallestValue, Value ());
}
switch (weight) {
case Weight.Lower: // Bias towards smaller values
return smallestValue;
case Weight.Upper: // Bias towards larger values
return 1 - smallestValue;
case Weight.Centre: // Bias towards middle values
return 0.5f + smallestValue * 0.5f * Sign ();
case Weight.Ends: // Bias towards smaller and larger values
return (Value () < 0.5f) ? smallestValue : 1 - smallestValue;
default:
Debug.LogError ("Missing weight implementation");
return 0;
}
}
// Returns the smallest of n random numbers between 0 and 1
public float SmallestRandom01 (int n) {
float smallest = 1;
for (int i = 0; i < n; i++) {
smallest = Mathf.Min (smallest, Value ());
}
return smallest;
}
// Returns the largest of n random numbers between 0 and 1
public float LargestRandom01 (int n) {
float largest = 0;
for (int i = 0; i < n; i++) {
largest = Mathf.Max (largest, Value ());
}
return largest;
}
// Returns the value closest to 0.5 out of n random numbers between 0 and 1
public float CentredRandom01 (int n) {
float mostCentredValue = 0;
for (int i = 0; i < n; i++) {
float value = Value ();
if (Mathf.Abs (value - 0.5f) < Mathf.Abs (mostCentredValue - 0.5f)) {
mostCentredValue = value;
}
}
return mostCentredValue;
}
public int Sign () {
return (prng.NextDouble () > 0.5) ? 1 : -1;
}
public int NextInt () {
return prng.Next ();
}
public Vector3 JiggleVector3 (float weightX, float weightY, float weightZ) {
return new Vector3 (SignedValue () * weightX, SignedValue () * weightY, SignedValue () * weightZ);
}
// Colours
public Color ColorHSV (float saturationMin, float saturationMax, float valueMin, float valueMax) {
float hue = Value ();
float saturation = Range (saturationMin, saturationMax);
float value = Range (valueMin, valueMax);
return Color.HSVToRGB (hue, saturation, value);
}
public Color ColorGreyscale (float valueMin, float valueMax) {
float value = Range (valueMin, valueMax);
return new Color (value, value, value);
}
// Elements
public T RandomElement<T> (T[] array) {
return array[Range (0, array.Length)];
}
public void Shuffle<T> (T[] array) {
int n = array.Length;
for (int i = 0; i < n - 1; i++) {
int j = prng.Next (i, n);
T temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
public void Shuffle<T> (List<T> list) {
int n = list.Count;
for (int i = 0; i < n - 1; i++) {
int j = prng.Next (i, n);
T temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ae686c76044de4891a2c6a36bf7434de
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,25 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class ShaderHelper {
// Set all values from settings object on the shader. Note, variable names must be an exact match in the shader.
// Settings object can be any class/struct containing vectors/ints/floats
public static void SetParams (System.Object settings, Material material, string variableNamePrefix = "") {
var fields = settings.GetType ().GetFields ();
foreach (var field in fields) {
var fieldType = field.FieldType;
string shaderVariableName = variableNamePrefix + field.Name;
if (fieldType == typeof (UnityEngine.Vector4) || fieldType == typeof (Vector3) || fieldType == typeof (Vector2)) {
material.SetVector (shaderVariableName, (Vector4) field.GetValue (settings));
} else if (fieldType == typeof (int)) {
material.SetInt (shaderVariableName, (int) field.GetValue (settings));
} else if (fieldType == typeof (float)) {
material.SetFloat (shaderVariableName, (float) field.GetValue (settings));
} else {
Debug.Log ($"Type {fieldType} not implemented");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7782a7a4791c8426aa102052d42c2541
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,22 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class TextureHelper {
public static void TextureFromGradient (Gradient gradient, int width, ref Texture2D texture) {
if (texture == null || texture.width != width || texture.height != 1) {
texture = new Texture2D (width, 1);
texture.filterMode = FilterMode.Bilinear;
texture.wrapMode = TextureWrapMode.Clamp;
}
Color[] colours = new Color[width];
for (int i = 0; i < width; i++) {
float t = i / (width - 1f);
colours[i] = gradient.Evaluate (t);
}
texture.SetPixels (colours);
texture.Apply ();
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ca4552dbbcdf04006b442ee84e5b2703
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: