I made a scene where balls appear in 3D space. Triangle balls spend a lot of resources. So I did this using 2d surfaces (quad) with a ball texture. But now I need to adjust the direction of the shape every time the camera moves. I do this using position transformation and the LookAt method. The question is can I optimize this? If it is possible to rotate the shapes with shader, this will greatly help.
using UnityEngine;
public class WorldSurf : MonoBehaviour
{
GameObject[] matrix;
int xSize = 20;
int ySize = 20;
int zSize = 20;
// Start is called before the first frame update
void Start()
{
matrix = new GameObject[xSize * ySize * zSize];
//var shader = Shader.Find("Legacy Shaders/Diffuse");
var shader = Shader.Find("Sprites/Default");
//var texture = Resources.Load<Texture>("Textures/Ball_01");
var i = 0;
for (var x = 0f; x < xSize; ++x)
{
for (var y = 0f; y < ySize; ++y)
{
for (var z = 0f; z < zSize; ++z)
{
var texture = Resources.Load<Texture>("Textures/Ball_" + ((int)Random.Range(0, 15)).ToString("00"));
matrix[i++] = CreateQuad(x * 3, y * 3, z * 3, shader, texture);
}
}
}
}
static GameObject CreateQuad(float x, float y, float z, Shader shader, Texture texture)
{
var quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
quad.transform.position = new Vector3(x, y, z);
quad.transform.forward = Camera.main.transform.forward;
var rend = quad.GetComponent<Renderer>();
rend.material.shader = shader;
rend.material.mainTexture = texture;
//rend.material.color = Color.red;
return quad;
}
// Update is called once per frame
void Update()
{
var pos = Camera.main.transform.position;
foreach (var itm in matrix)
{
itm.transform.LookAt(pos);
}
}
}
Generally yes, and in this specific case where you want a quad to align with the camera makes doing so very easy.
What you want is called a "billboard shader". Here is an example from Wikibooks:
Shader "Cg shader for billboards" {
Properties {
_MainTex ("Texture Image", 2D) = "white" {}
_ScaleX ("Scale X", Float) = 1.0
_ScaleY ("Scale Y", Float) = 1.0
}
SubShader {
Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// User-specified uniforms
uniform sampler2D _MainTex;
uniform float _ScaleX;
uniform float _ScaleY;
struct vertexInput {
float4 vertex : POSITION;
float4 tex : TEXCOORD0;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 tex : TEXCOORD0;
};
vertexOutput vert(vertexInput input)
{
vertexOutput output;
output.pos = mul(UNITY_MATRIX_P,
mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0))
+ float4(input.vertex.x, input.vertex.y, 0.0, 0.0)
* float4(_ScaleX, _ScaleY, 1.0, 1.0));
output.tex = input.tex;
return output;
}
float4 frag(vertexOutput input) : COLOR
{
return tex2D(_MainTex, float2(input.tex.xy));
}
ENDCG
}
}
}
And an explanation of how this works:
The basic idea is to transform only the origin ( 0 , 0 , 0 , 1 )
of the object
space to view space with the standard model-view transformation
UNITY_MATRIX_MV. (In homogeneous coordinates all points have a 1 as
fourth coordinate; see the discussion in Section “Vertex
Transformations”.) View space is just a rotated version of world space
with the xy plane parallel to
the view plane as discussed in Section “Vertex Transformations”. Thus,
this is the correct space to construct an appropriately rotated
billboard. We subtract the x y object coordinates (vertex.x and vertex.y) from the transformed
origin in view coordinates and then transform the result with the
projection matrix UNITY_MATRIX_P.
This will produce an output like this:
Related
This a jelly shader from unity asset store yet I cant figure out how to make it always active as it requires 2 vector3 (_ModelOrigin and a __ImpactOrigin). Any ideas on how to edit it is always active?
Thats how I use it right now :
modelRenderer.material.SetVector("_ModelOrigin", pos.transform.position);
modelRenderer.material.SetVector("_ImpactOrigin", pos.transform.position += new Vector3(0.001f, 0.001f, 0.001f));
but when the gameobject mesh is too far it stops working
I tried also to just use transform.position but when I move the gameobject the shader get new values so it becomes laggy for a second
Thanks
// Upgrade NOTE: upgraded instancing buffer 'Props' to new syntax.
Shader "Custom/JellyShader" {
Properties{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo (RGB)", 2D) = "white" {}
_Glossiness("Smoothness", Range(0,1)) = 0.5
_Metallic("Metallic", Range(0,1)) = 0.0
_Transparency("Transparency", float) = 0.1
_ControlTime("Time", float) = 0
_ModelOrigin("Model Origin", Vector) = (0,0,0,0)
_ImpactOrigin("Impact Origin", Vector) = (-5,0,0,0)
_Emission("Emission", float) = 0
[HDR] _EmissionColor("Color", Color) = (0,0,0)
_Frequency("Frequency", Range(0, 1000)) = 10
_Amplitude("Amplitude", Range(0, 5)) = 0.1
_WaveFalloff("Wave Falloff", Range(1, 8)) = 4
_MaxWaveDistortion("Max Wave Distortion", Range(0.1, 2.0)) = 1
_ImpactSpeed("Impact Speed", Range(0, 10)) = 0.5
_WaveSpeed("Wave Speed", Range(-10, 10)) = -5
}
SubShader{
Tags { "Queue" = "Transparent" "RenderType" = "Transparent" }
LOD 200
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows addshadow vertex:vert alpha:fade
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
sampler2D _MainTex;
struct Input {
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
fixed4 _Color;
fixed4 _EmissionColor;
float _ControlTime;
float4 _ModelOrigin;
float4 _ImpactOrigin;
float _Transparency;
half _Frequency; //Base frequency for our waves.
half _Amplitude; //Base amplitude for our waves.
half _WaveFalloff; //How quickly our distortion should fall off given distance.
half _MaxWaveDistortion; //Smaller number here will lead to larger distortion as the vertex approaches origin.
half _ImpactSpeed; //How quickly our wave origin moves across the sphere.
half _WaveSpeed; //Oscillation speed of an individual wave.
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_BUFFER_END(Props)
void vert(inout appdata_base v) {
float4 world_space_vertex = mul(unity_ObjectToWorld, v.vertex);
float4 direction = normalize(_ModelOrigin - _ImpactOrigin);
float4 origin = _ImpactOrigin + _ControlTime * _ImpactSpeed * direction;
//Get the distance in world space from our vertex to the wave origin.
float dist = distance(world_space_vertex, origin);
//Adjust our distance to be non-linear.
dist = pow(dist, _WaveFalloff);
//Set the max amount a wave can be distorted based on distance.
dist = max(dist, _MaxWaveDistortion);
//Convert direction and _ImpactOrigin to model space for later trig magic.
float4 l_ImpactOrigin = mul(unity_WorldToObject, _ImpactOrigin);
float4 l_direction = mul(unity_WorldToObject, direction);
//Magic
float impactAxis = l_ImpactOrigin + dot((v.vertex - l_ImpactOrigin), l_direction);
v.vertex.xyz += v.normal * sin(impactAxis * _Frequency + _ControlTime * _WaveSpeed) * _Amplitude * (1 / dist);
}
void surf(Input IN, inout SurfaceOutputStandard o) {
// Albedo comes from a texture tinted by color
fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
o.Emission = c.rgb * tex2D(_MainTex, IN.uv_MainTex).a * _EmissionColor;
o.Smoothness = _Glossiness;
}
ENDCG
}
FallBack "Diffuse"
}
Simplest solution is to just remove them as properties and calculate the model pos based on the object to world transform and then use your offset to set the impact origin.
That way you don't need to set those parameters in c#, it should "just work".
// Upgrade NOTE: upgraded instancing buffer 'Props' to new syntax.
Shader "Custom/JellyShader" {
Properties{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo (RGB)", 2D) = "white" {}
_Glossiness("Smoothness", Range(0,1)) = 0.5
_Metallic("Metallic", Range(0,1)) = 0.0
_Transparency("Transparency", float) = 0.1
_ControlTime("Time", float) = 0
_Emission("Emission", float) = 0
[HDR] _EmissionColor("Color", Color) = (0,0,0)
_Frequency("Frequency", Range(0, 1000)) = 10
_Amplitude("Amplitude", Range(0, 5)) = 0.1
_WaveFalloff("Wave Falloff", Range(1, 8)) = 4
_MaxWaveDistortion("Max Wave Distortion", Range(0.1, 2.0)) = 1
_ImpactSpeed("Impact Speed", Range(0, 10)) = 0.5
_WaveSpeed("Wave Speed", Range(-10, 10)) = -5
}
SubShader{
Tags { "Queue" = "Transparent" "RenderType" = "Transparent" }
LOD 200
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows addshadow vertex:vert alpha:fade
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
sampler2D _MainTex;
struct Input {
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
fixed4 _Color;
fixed4 _EmissionColor;
float _ControlTime;
float _Transparency;
half _Frequency; //Base frequency for our waves.
half _Amplitude; //Base amplitude for our waves.
half _WaveFalloff; //How quickly our distortion should fall off given distance.
half _MaxWaveDistortion; //Smaller number here will lead to larger distortion as the vertex approaches origin.
half _ImpactSpeed; //How quickly our wave origin moves across the sphere.
half _WaveSpeed; //Oscillation speed of an individual wave.
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_BUFFER_END(Props)
void vert(inout appdata_base v) {
float4 world_space_vertex = mul(unity_ObjectToWorld, v.vertex);
// hardcoded stuff:
float4 _ModelOrigin = mul(unity_ObjectToWorld, float4(0,0,0,1));
float4 _ImpactOffset = float4(0.001, 0.001, 0.001, 0);
float4 _ImpactOrigin = _ModelOrigin + _ImpactOffset;
float4 direction = normalize(_ModelOrigin - _ImpactOrigin);
float4 origin = _ImpactOrigin + _ControlTime * _ImpactSpeed * direction;
//Get the distance in world space from our vertex to the wave origin.
float dist = distance(world_space_vertex, origin);
//Adjust our distance to be non-linear.
dist = pow(dist, _WaveFalloff);
//Set the max amount a wave can be distorted based on distance.
dist = max(dist, _MaxWaveDistortion);
//Convert direction and _ImpactOrigin to model space for later trig magic.
float4 l_ImpactOrigin = mul(unity_WorldToObject, _ImpactOrigin);
float4 l_direction = mul(unity_WorldToObject, direction);
//Magic
float impactAxis = l_ImpactOrigin + dot((v.vertex - l_ImpactOrigin), l_direction);
v.vertex.xyz += v.normal * sin(impactAxis * _Frequency + _ControlTime * _WaveSpeed) * _Amplitude * (1 / dist);
}
void surf(Input IN, inout SurfaceOutputStandard o) {
// Albedo comes from a texture tinted by color
fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
o.Emission = c.rgb * tex2D(_MainTex, IN.uv_MainTex).a * _EmissionColor;
o.Smoothness = _Glossiness;
}
ENDCG
}
FallBack "Diffuse"
}
Note: Please let me know if this has any syntax errors; it has been a minute since I've done shader code.
I tried to learn from this tutorial : Writing Shaders In Unity
The shader code :
Shader "Custom/TerrainCircle"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_MainColor("Main Color", Color) = (0, 1, 0)
_CircleColor("Circle Color", Color) = (1, 0, 0)
_Center("Center", Vector) = (0,0,0,0)
_Radius("Radius", Range(0, 100)) = 10
_Thickness("Thickness", Range(0, 100)) = 5
}
SubShader
{
CGPROGRAM
#pragma surface surfaceFunc Lambert
sampler2D _MainTex;
fixed3 _MainColor;
fixed3 _CircleColor;
float3 _Center;
float _Thickness;
float _Radius;
struct Input {
float2 uv_MainTex;
float3 worldPos;
};
void surfaceFunc(Input IN, inout SurfaceOutput o) {
half4 c = tex2D(_MainTex, IN.uv_MainTex);
float dist = distance(_Center, IN.worldPos);
if (dist > _Radius && dist < (_Radius + _Thickness))
o.Albedo = _CircleColor;
else
o.Albedo = c.rgb;
o.Alpha = c.a;
}
ENDCG
}
}
Then I created a Shader file with the code and a material. Added the Shader to the material.
Then dragged the material to the terrain.
Two problems :
When dragging the material to the terrain it put the material only on small part of the terrain on this rock in white. Why it's not applying the material over the whole terrain ?
It's not showing the circle at all. Nothing is drawn. Not even close to the tutorial video in the link.
I moved the terrain to the side since the rocks and cliffs are from another asset. But now I can't drag the material over the terrain. The terrain is not accepting the material at all.
Still not working not drawing the circle on the terrain.
I tried with a new terrain : Terrain (1)
Added the New Material :
This is the material settings :
This is the shader settings :
And the shader code :
Shader "Custom/TerrainCircle"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_MainColor("Main Color", Color) = (0, 1, 0)
_CircleColor("Circle Color", Color) = (1, 0, 0)
_Center("Center", Vector) = (0,0,0,0)
_Radius("Radius", Range(0, 100)) = 10
_Thickness("Thickness", Range(0, 100)) = 5
}
SubShader
{
CGPROGRAM
#pragma surface surfaceFunc Lambert
sampler2D _MainTex;
fixed3 _MainColor;
fixed3 _CircleColor;
float3 _Center;
float _Thickness;
float _Radius;
struct Input {
float2 uv_MainTex;
float3 worldPos;
};
void surfaceFunc(Input IN, inout SurfaceOutput o) {
half4 c = tex2D(_MainTex, IN.uv_MainTex);
float dist = distance(_Center, IN.worldPos);
if (dist > _Radius && dist < (_Radius + _Thickness))
o.Albedo = _CircleColor;
else
o.Albedo = c.rgb;
o.Alpha = c.a;
}
ENDCG
}
}
The shader type I created is : Standard Surface Shader
Solution I had to create a mono script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class CircleOnTerrain : MonoBehaviour
{
public Material radiusMaterial;
public float radius = 1;
public Color color = Color.white;
public Color circleColor = Color.blue;
public float thickness = 1;
void Update()
{
radiusMaterial.SetVector("_Center", transform.position);
radiusMaterial.SetFloat("_Radius", radius);
radiusMaterial.SetColor("_MainColor", color);
radiusMaterial.SetColor("_CircleColor", circleColor);
radiusMaterial.SetFloat("_Thickness", thickness);
}
}
Attached the script to a 3d cube and now it's working.
Add your material to the terrain like so:
I'm trying to make a game with periodic boundary conditions (so basically if you are on the right edge of the map, and you look right, you should see the whole map again).
I made a geometry shader which takes one triangle and outputs the 27 triangles i need (3*3*3 periodic box), and it works perfectly while the base object is on the screen. As soon as the base object leaves the screen all the copies disappear too.
So i think unity does not even call my shaders on the vertices which is behind my camera (which is totally fine for optimization), but with my current solution i need a call on every object of the game.
Is it possible to force unity not to discard any objects before rendering, or should i look for a different solution? If i have to do something else, do you have any ideas?
Here's my current code. (I'm new with shaders, so it might be stupid...)
Shader "Unlit/Geom_shader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma geometry geom
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata {
float4 vertex : POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD0;
};
struct v2g {
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
struct g2f {
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2g vert (appdata v)
{
v2g o;
o.vertex = v.vertex;
o.uv = v.uv;
return o;
}
[maxvertexcount(3*3*3*3)]
void geom(triangle v2g input[3], inout TriangleStream<g2f> tristream) {
g2f o = (g2f)0;
for (int x = 0; x < 3; x++)
{
float x_shift = (x - 1) * 2*_SinTime[2];
for (int y = 0; y < 3; y++)
{
float y_shift = (y - 1) * 2 * _SinTime[2];
for (int z = 0; z < 3; z++)
{
float z_shift = (z - 1) * 2 * _CosTime[2];
for (int i = 0; i < 3; i++)
{
o.vertex = UnityObjectToClipPos(input[i].vertex + float4(x_shift, y_shift, z_shift, 0));
o.uv = TRANSFORM_TEX(input[i].uv, _MainTex);
tristream.Append(o);
}
tristream.RestartStrip();
}
}
}
}
fixed4 frag (g2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
return col;
}
ENDCG
}
}
}
I'm not trying to use it for lights but for whole objects and i'm sure they are handled differently. So the reason why it is happening is the same, but the solution must be different. (Why it's not a duplicate of: Unity3D - Light deactivated when facing opposite direction )
It's not the vertices being discarded, it's the entire mesh being culled as a whole.
Unity implements View Frustum Culling based on the bounding box of your mesh. You can change the bounding box of a mesh manually by assigning a new value to Mesh.bounds.
I am building a Polygon Tool using Unity 5.5 and WebGL, which I would like to use to crop a selection from an image. The project is using a shader file to define the points and area which make up the polygon. You can see the code for the shader below, as well as the code file.
The problem I am currently experiencing is that the project works fine in the Editor, but the WebGL build shows up pink in the browser. The polygon shader doesn't render, if I set a Fallback shader in the file it loads that one. I've looked up the issue online and I found and tried the following:
Reimport all assets, as something may be missing. Check all game objects in the hierarchy for broken references.
Make sure the shaders are in the ‘Always Included Shaders’ list in Project Graphics Settings.
Potential memory leak? I increased the number of MB allocated to the project to 1024, lowered the size of the textures by compressing them and also ran the Profiler in the Editor. The Profiler recorded a max total use of ~220MB.
Toggled the Quality Settings - I discovered that the Shader does not work if Anti-Aliasing is not on.
Graphics card not supporting the shader? People online have reported similar problems on OS X (which I am also using), but they have not updated their queries.
I should note that there are no errors or warnings in the project. I am unsure where the problem lays and would truly appreciate any take on this issue. Please let me know if there is any further information that I can provide which could ease the process! Thank you in advance for your help :)
Polygon.cs file:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class Polygon : MonoBehaviour {
public Material mat; //Binding materials; Polygon shader applied to it.
Vector3[] worldPos; //Store 3D coordinates
Vector4[] screenPos; //Store to draw the polygon vertices in screen coordinates
int maxPointNum = 6; //Total number of polygon vertices
int currentpointNum = 0; //Current number of points placed
int pointNum2Shader = 0; //Transfer number of vertices to shader
bool InSelection = true; //Vertex gets is in the process
void Start() {
worldPos = new Vector3[maxPointNum];
screenPos = new Vector4[maxPointNum];
}
void Update() {
mat.SetVectorArray("Value", screenPos); //Pass the vertex position information to the screen shader.
mat.SetInt("PointNum", pointNum2Shader); //Transfer number of vertices to shader
//Cameras fired a ray to get to select a 3D location
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100)) {
Debug.DrawLine(ray.origin, hit.point);
}
//Use mouse clicks to obtain location information
if (Input.GetMouseButtonDown(0) && InSelection) {
if (currentpointNum < maxPointNum) {
currentpointNum++;
pointNum2Shader++;
worldPos[currentpointNum - 1] = hit.point;
//Vector3 v3 = Camera.main.ScreenToWorldPoint (worldPos [currentpointNum-1]);
Vector3 v3 = Camera.main.WorldToScreenPoint(worldPos[currentpointNum - 1]);
screenPos[currentpointNum - 1] = new Vector4(v3.x, v3.y, v3.z, 0);
}
else {
InSelection = false;
}
}
//Updated in real time screens of 3D point selected location
for (int i = 0; i < maxPointNum; i++) {
Vector3 v3 = Camera.main.WorldToScreenPoint(worldPos[i]);
screenPos[i] = new Vector4(v3.x, v3.y, v3.z, 0);
}
//Detect if 3d point is behind the camera, if you stop drawing
for (int i = 0; i < currentpointNum; i++) {
if (Vector3.Dot(worldPos[i] - Camera.main.transform.position, Camera.main.transform.forward) <= 0) {
pointNum2Shader = 0;
break;
}
pointNum2Shader = currentpointNum;
}
}
//Grab the current rendering of image processing
void OnRenderImage(RenderTexture src, RenderTexture dest) {
Graphics.Blit(src, dest, mat);
}
void OnGUI () {
float btnWidth = 100;
float btnHeight = 50;
float y = 150;
if (GUI.Button(new Rect(100, y, btnWidth, btnHeight), "Crop")) {
Vector2[] vertices2D = new Vector2[maxPointNum];
for (int i = 0; i < currentpointNum; i++) {
vertices2D[i].x = worldPos[i].x;
vertices2D[i].y = worldPos[i].y;
}
// Use the triangulator to get indices for creating triangles
Triangulator tr = new Triangulator(vertices2D);
int[] indices = tr.Triangulate();
GameObject plane = GameObject.Find("Plane");
MeshFilter filter = plane.GetComponent<MeshFilter>();
Vector3[] vertices = filter.mesh.vertices;
// Vector2[] texCoords = new Vector2[currentpointNum];
// for(int i = 0; i < currentpointNum; i++) {
// //There should be as many texture coordinates as vertices.
// //This example does not support textures, so fill with zeros
// texCoords[i] = new Vector2(vertices[i].x, vertices[i].y);
// }
// Create the mesh
Mesh msh = new Mesh();
msh.vertices = worldPos;
msh.triangles = indices;
msh.RecalculateNormals();
msh.RecalculateBounds();
filter.mesh = msh;
}
}
}
Polygon.shader file:
Shader "Unlit/polygon"
{
Properties
{
//Define basic properties can be set from inside the editor variable
//_MainTex ("Texture", 2D) = "white" {}
}
CGINCLUDE
// Upgrade NOTE: excluded shader from DX11 because it uses wrong array syntax (type[size] name)
#pragma exclude_renderers d3d11
//Incoming vertices function from the application data structure definitions
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
//Incoming segment from a vertex function from the data structure definitions
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
//Define mapping variables
sampler2D _MainTex;
// float4 _MainTex_ST;
//Define variables for communicating with the script
uniform float4 Value[6];
int PointNum = 0;
//Function that calculates the distance between two points
float Dis(float4 v1,float4 v2)
{
return sqrt(pow((v1.x-v2.x),2)+pow((v1.y-v2.y),2));
}
//Draw line segments
bool DrawLineSegment(float4 p1, float4 p2, float lineWidth,v2f i)
{
float4 center = float4((p1.x+p2.x)/2,(p1.y+p2.y)/2,0,0);
//Calculate distance between point and line
float d = abs((p2.y-p1.y)*i.vertex.x + (p1.x - p2.x)*i.vertex.y +p2.x*p1.y -p2.y*p1.x )/sqrt(pow(p2.y-p1.y,2) + pow(p1.x-p2.x,2));
//When less than or equal to half the line width, which belongs to the linear range, return true
float lineLength = sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2));
if(d<=lineWidth/2 && Dis(i.vertex,center)<lineLength/2)
{
return true;
}
return false;
}
//To draw a polygon, this limits the number of vertices is not more than 6. You can change.
bool pnpoly(int nvert, float4 vert[6], float testx, float testy)
{
int i, j;
bool c=false;
float vertx[6];
float verty[6];
for(int n=0;n<nvert;n++)
{
vertx[n] = vert[n].x;
verty[n] = vert[n].y;
}
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
v2f vert (appdata v)
{
v2f o;
//Object vertices from model space to the camera cut space, or you can use the shorthand way:
//o.vertex = UnityObjectToClipPos(v.vertex);
o.vertex = mul(UNITY_MATRIX_MVP,v.vertex);
//2D UV coordinate transformation can also use shorthand methods
//o.uv = TRANSFORM_TEX(v.uv, _MainTex);
//o.uv = v.uv.xy * _MainTex_ST.xy + _MainTex_ST.zw;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
//Draw a polygon vertex
for(int j=0;j<PointNum;j++)
{
if(Dis(i.vertex, Value[j])<3)
{
return fixed4(1,0,0,0.5);
}
}
//Draws the edges of the polygon
for(int k=0;k<PointNum;k++)
{
if(k==PointNum-1)
{
if(DrawLineSegment(Value[k],Value[0],2,i))
{
return fixed4(1,1,0,0.5);
}
}
else
{
if(DrawLineSegment(Value[k],Value[k+1],2,i))
{
return fixed4(1,1,0,0.5);
}
}
}
//Within the filled polygon
if(pnpoly(PointNum, Value,i.vertex.x ,i.vertex.y))
{
return fixed4(0,1,0,0.3);
}
return fixed4(0,0,0,0);
//fixed4 col = tex2D(_MainTex, i.uv);
//return col;
}
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
//Select Alpha blend mode
Blend SrcAlpha OneMinusSrcAlpha
//In the CGPROGRAM block of code to write your own processes
CGPROGRAM
//Defined segment function entry and vertex function respectively, Vert and Frag
#pragma vertex vert
#pragma fragment frag
//Contains the basic files, there are some macro definitions and basic functions
#include "UnityCG.cginc"
ENDCG
}
}
}
Pink appearance means your build has missing material assignments on the mesh renderer component or missing shader in the build.
If you are assigning materials or shaders at runtime, make sure you include the shader in the build.
You can force unity to include any shader by adding it to the list in Edit/Project Settings/Graphics
Im creating a pretty simple game in Unity3d where I need to create multiple Meshes. The code that I create is pretty simple and yet after having more than 8 Meshes at the same time, the peerformance reduces considerably to just a couple of fps (~8 fps). The Mesh that I create is just a simple square so I really don´t know where the problem is, here´s my code:
using UnityEngine;
using System.Collections;
public class TetraGenerator : MonoBehaviour {
public int slices;
public GameObject forceSource;
void OnMouseDown(){
var arcLength = Mathf.PI / slices;
var distance = 10;
var height = 1;
var origin = Random.Range(-slices,slices);
Vector3[] vertices = new Vector3[4];
vertices [0] = new Vector3 (Mathf.Cos(origin*arcLength),Mathf.Sin(origin*arcLength));
vertices [1] = new Vector3 (Mathf.Cos(origin*arcLength),Mathf.Sin(origin*arcLength));
vertices [2] = new Vector3 (Mathf.Cos((origin+1)*arcLength),Mathf.Sin((origin+1)*arcLength));
vertices [3] = new Vector3 (Mathf.Cos((origin+1)*arcLength),Mathf.Sin((origin+1)*arcLength));
vertices [0] *= distance;
vertices [1] *= (distance+height);
vertices [2] *= (distance+height);
vertices [3] *= distance;
Vector3 frameRef = new Vector3(Mathf.Cos(origin*arcLength+(arcLength/2)),Mathf.Sin(origin*arcLength+(arcLength/2)));
frameRef *= distance;
vertices [0] -= frameRef;
vertices [1] -= frameRef;
vertices [2] -= frameRef;
vertices [3] -= frameRef;
int[] triangles = new int[]{0,1,2,2,3,0};
Mesh mesh = new Mesh ();
mesh.vertices = vertices;
mesh.triangles = triangles;
GameObject tile = new GameObject("tile",typeof(MeshFilter),typeof(MeshRenderer));
tile.transform.position = frameRef;
MeshFilter meshFilter = tile.GetComponent<MeshFilter> ();
meshFilter.mesh = mesh;
}
}
Your problem is that you are not setting a material or that you dont provide everything the material needs like uv coordinates or vertex colors. I am not sure if its the error messages in the Debug.Log or if the shader itself is causing the low framerate, but to test it you can use:
// enter this at the top and set the material in the inspector
public Material mat;
[...]
// enter this at the bottom
MeshRenderer meshRenderer = tile.GetComponent<MeshRenderer>();
meshRenderer.material = mat;
and as material you create a new one and use a shader with this code:
Shader "SimpleShader"
{
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct vertexInput
{
float4 pos : POSITION;
};
struct vertexOutput
{
float4 pos : SV_POSITION;
float4 col : COLOR0;
};
vertexOutput vert(vertexInput input)
{
vertexOutput output;
output.pos = mul(UNITY_MATRIX_MVP, input.pos);
output.col = float4(1, 0, 0, 1);
return output;
}
float4 frag(vertexOutput input) : COLOR
{
return input.col;
}
ENDCG
}
}
}