Esempio n. 1
0
    public void MakeBody()
    {
        flags        = new CreatureRawFlags(race.flags);
        bodyCategory = FindBodyCategory(caste);
        if (spawnedParts.Count > 0)
        {
            foreach (var part in spawnedParts)
            {
                Destroy(part.Value.gameObject);
            }
            spawnedParts.Clear();
        }
        float scale = caste.adult_size / (float)caste.total_relsize * 10;

        if (unit != null && unit.size_info != null)
        {
            scale = unit.size_info.size_cur / (float)caste.total_relsize * 10;
        }
        MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();

        bodyScale = BodyDefinition.GetBodyScale(bodyCategory, race, caste);

        Vector3 unitShape = Vector3.one;

        for (int i = 0; i < caste.body_appearance_modifiers.Count; i++)
        {
            var mod   = caste.body_appearance_modifiers[i];
            int value = 100;
            if (unit != null && unit.appearance != null)
            {
                value = unit.appearance.body_modifiers[i];
            }
            else
            {
                value = UnityEngine.Random.Range(mod.mod_min, mod.mod_max);
            }
            switch (mod.type)
            {
            case "BROADNESS":
                unitShape.x = value / 100f;
                break;

            case "HEIGHT":
                unitShape.y = value / 100f;
                break;

            case "LENGTH":
                unitShape.z = value / 100f;
                break;

            default:
                break;
            }
        }

        bodyScale = BodyPart.MultiplyScales(bodyScale, unitShape);

        for (int i = 0; i < caste.body_parts.Count; i++)
        {
            var part = caste.body_parts[i];
            if (part.flags[(int)BodyPartFlags.BodyPartRawFlags.INTERNAL])
            {
                continue;
            }

            var spawnedPart = new GameObject().AddComponent <BodyPart>();
            spawnedPart.name     = string.Format("{0} ({1})", part.token, part.category);
            spawnedPart.token    = part.token;
            spawnedPart.category = part.category;
            spawnedPart.flags    = new BodyPartFlags(part.flags);
            spawnedPart.volume   = part.relsize * scale;
            spawnedPart.layers   = part.layers;



            var model = BodyDefinition.GetPart(bodyCategory, race, caste, part);
            if (model != null)
            {
                var placedModel = Instantiate(model);
                placedModel.transform.SetParent(spawnedPart.transform);
                placedModel.CollectEquipment();
                spawnedPart.modeledPart = placedModel;
            }

            if (spawnedPart.modeledPart == null)
            {
                var cube = GameObject.CreatePrimitive(PrimitiveType.Cube).AddComponent <VolumeKeeper>();
                if ((Application.isPlaying))
                {
                    Destroy(cube.GetComponent <BoxCollider>());
                }
                else
                {
                    DestroyImmediate(cube.GetComponent <BoxCollider>());
                }

                cube.name = spawnedPart.name + " cube";
                cube.transform.SetParent(spawnedPart.transform);
                cube.volume = spawnedPart.volume;
                cube.FixVolume();
                cube.gameObject.AddComponent <BodyLayer>();
                spawnedPart.placeholder = cube;
                if (skinMat == null)
                {
                    skinMat = Resources.Load <Material>("Skin");
                }
                cube.GetComponent <MeshRenderer>().sharedMaterial = skinMat;
            }
            if (spawnedPart.flags.upperbody)
            {
                upperBody = spawnedPart;
                foreach (var item in spawnedPart.GetComponentsInChildren <BodyPartChildPlaceholder>())
                {
                    if (item.category == ":ATTACH:")
                    {
                        riderPosition = item.transform;
                        break;
                    }
                }
            }
            if (spawnedPart.flags.lowerbody)
            {
                lowerBody = spawnedPart;
            }
            var modeledLayers = spawnedPart.GetComponentsInChildren <BodyLayer>();
            foreach (var layer in part.layers)
            {
                var matchedLayers = Array.FindAll(modeledLayers, x => x.layerName == layer.layer_name);
                if (matchedLayers.Length == 0)
                {
                    matchedLayers = Array.FindAll(modeledLayers, x => string.IsNullOrEmpty(x.layerName));
                    if (matchedLayers.Length < 0)
                    {
                        spawnedPart.layerModels.Add(null);
                    }
                    else
                    {
                        bool matchedAny = false;
                        foreach (var matchedLayer in matchedLayers)
                        {
                            if (!matchedLayer.placed)
                            {
                                matchedLayer.layerRaw = layer;
                                spawnedPart.layerModels.Add(matchedLayer);
                                matchedLayer.placed = true;
                                matchedAny          = true;
                                break;
                            }
                        }
                        if (!matchedAny)
                        {
                            spawnedPart.layerModels.Add(null);
                        }
                    }
                }
                else
                {
                    bool matchedAny = false;
                    foreach (var matchedLayer in matchedLayers)
                    {
                        if (!matchedLayer.placed)
                        {
                            matchedLayer.layerRaw = layer;
                            spawnedPart.layerModels.Add(matchedLayer);
                            matchedLayer.placed = true;
                            matchedAny          = true;
                            break;
                        }
                    }
                    if (!matchedAny)
                    {
                        spawnedPart.layerModels.Add(null);
                    }
                }
            }
            foreach (var modeledLayer in modeledLayers)
            {
                if (!modeledLayer.placed)
                {
                    modeledLayer.gameObject.SetActive(false);
                }
            }

            foreach (var layerModel in spawnedPart.layerModels)
            {
                if (layerModel == null)
                {
                    continue;
                }
                var renderer = layerModel.GetComponentInChildren <MeshRenderer>();
                if (renderer != null)
                {
                    var tissue = race.tissues[layerModel.layerRaw.tissue_id];
                    var color  = ContentLoader.GetColor(tissue.material);
                    var index  = ContentLoader.GetPatternIndex(tissue.material);
                    propertyBlock.SetColor("_MatColor", color);
                    propertyBlock.SetFloat("_MatIndex", index);
                    renderer.SetPropertyBlock(propertyBlock);
                }
            }
            spawnedParts[i] = spawnedPart;
        }
        for (int modNum = 0; modNum < caste.modifier_idx.Count; modNum++)
        {
            if (!spawnedParts.ContainsKey(caste.part_idx[modNum]))
            {
                continue;
            }
            var mod  = caste.modifiers[caste.modifier_idx[modNum]];
            var part = spawnedParts[caste.part_idx[modNum]];
            if (caste.layer_idx[modNum] >= 0)
            {
                var layer = part.layerModels[caste.layer_idx[modNum]];
                if (layer != null)
                {
                    layer.mods.Add(new BodyPart.ModValue(mod, modNum));
                }
            }
            else
            {
                part.mods.Add(new BodyPart.ModValue(mod, modNum));
            }
        }

        for (int modNum = 0; modNum < caste.color_modifiers.Count; modNum++)
        {
            var colorMod = caste.color_modifiers[modNum];
            //Temp fix until actual creatures are being read.
            if (colorMod.start_date > 0)
            {
                continue;
            }
            int seed = Mathf.Abs(GetInstanceID() * modNum) % colorMod.patterns.Count;
            for (int i = 0; i < colorMod.body_part_id.Count; i++)
            {
                var part = spawnedParts[colorMod.body_part_id[i]];
                if (part == null || !part.gameObject.activeSelf)
                {
                    continue;
                }
                var layer = part.layerModels[colorMod.tissue_layer_id[i]];
                if (layer == null || !layer.gameObject.activeSelf)
                {
                    continue;
                }
                ColorDefinition colorDef;
                if (unit != null && unit.appearance != null)
                {
                    colorDef = colorMod.patterns[unit.appearance.colors[modNum]].colors[0];
                }
                else
                {
                    colorDef = colorMod.patterns[seed].colors[0];
                }
                var color = new Color32((byte)colorDef.red, (byte)colorDef.green, (byte)colorDef.blue, 128);
                var index = ContentLoader.GetPatternIndex(race.tissues[layer.layerRaw.tissue_id].material);
                propertyBlock.SetColor("_MatColor", color);
                propertyBlock.SetFloat("_MatIndex", index);
                var renderer = layer.GetComponentInChildren <MeshRenderer>();
                if (renderer != null)
                {
                    renderer.SetPropertyBlock(propertyBlock);
                }
            }
        }
        for (int i = 0; i < caste.body_parts.Count; i++)
        {
            if (!spawnedParts.ContainsKey(i))
            {
                continue;
            }
            var part = caste.body_parts[i];
            if (!spawnedParts.ContainsKey(part.parent))
            {
                spawnedParts[i].transform.SetParent(transform);
            }
            else
            {
                spawnedParts[i].transform.SetParent(spawnedParts[part.parent].transform);
                spawnedParts[i].parent = spawnedParts[part.parent];
                spawnedParts[part.parent].children.Add(spawnedParts[i]);
            }
            if (part.parent < 0)
            {
                rootPart = spawnedParts[i];
            }
            if (spawnedParts[i].flags.stance)
            {
                stanceCount++;
            }
        }

        if (rootPart == null)
        {
            return; //There's no root part, means there's no body.
        }
        //Use this when we do body part mods.
        //for(int i = 0; i < caste.modifier_idx.Count; i++)
        //{
        //    var modifier = caste.modifiers[caste.modifier_idx[i]];
        //    var part = caste.body_parts[caste.part_idx[i]];
        //}


        rootPart.Arrange(this);
        bounds = rootPart.GetComponentInChildren <MeshRenderer>().bounds;
        foreach (var item in rootPart.GetComponentsInChildren <MeshRenderer>())
        {
            bounds.Encapsulate(item.bounds);
        }
        rootPart.transform.localPosition = new Vector3(0, -bounds.min.y, 0);
    }
        private void BuildWindow()
        {
            // Initialize property block state.
            int colorID = Shader.PropertyToID("_Color");

            propertyBlockFrameTarget = new MaterialPropertyBlock();
            propertyBlockFrameTarget.SetColor(colorID, targetFrameRateColor);
            propertyBlockFrameMissed = new MaterialPropertyBlock();
            propertyBlockFrameMissed.SetColor(colorID, missedFrameRateColor);

            // Build the window root.
            {
                window = CreateQuad("VisualProfiler", null);
                window.transform.parent = WindowParent;
                InitializeRenderer(window, backgroundMaterial, colorID, baseColor);
                window.transform.localScale = new Vector3(0.2f, 0.04f, 1.0f);
                windowRotation = Quaternion.AngleAxis(windowYawRotation, Vector3.right);
            }

            // Add frame rate text and frame indicators.
            {
                frameRateText = CreateText("FrameRateText", new Vector3(-0.495f, 0.5f, 0.0f), window.transform, TextAnchor.UpperLeft, textMaterial, Color.white, string.Empty);

                frameInfo = new FrameInfo[frameRange];
                Vector3 scale    = new Vector3(1.0f / frameRange, 0.2f, 1.0f);
                Vector3 position = new Vector3(0.5f - (scale.x * 0.5f), 0.15f, 0.0f);

                for (int i = 0; i < frameRange; ++i)
                {
                    frameInfo[i] = new FrameInfo();
                    frameInfo[i].PropertyBlock = propertyBlockFrameTarget;

                    GameObject quad = CreateQuad("Frame", window.transform);
                    frameInfo[i].Renderer = InitializeRenderer(quad, defaultMaterial, colorID, missedFrameRateColor);

                    quad.transform.localPosition = position;
                    Vector3 bufferedScale = new Vector3(scale.x * 0.8f, scale.y, scale.z);
                    quad.transform.localScale = bufferedScale;

                    position.x -= scale.x;
                }
            }

            // Add memory usage text and bars.
            {
                usedMemoryText  = CreateText("UsedMemoryText", new Vector3(-0.495f, 0.0f, 0.0f), window.transform, TextAnchor.UpperLeft, textMaterial, memoryUsedColor, usedMemoryString);
                peakMemoryText  = CreateText("PeakMemoryText", new Vector3(0.0f, 0.0f, 0.0f), window.transform, TextAnchor.UpperCenter, textMaterial, memoryPeakColor, peakMemoryString);
                limitMemoryText = CreateText("LimitMemoryText", new Vector3(0.495f, 0.0f, 0.0f), window.transform, TextAnchor.UpperRight, textMaterial, Color.white, limitMemoryString);

                GameObject limitBar = CreateQuad("LimitBar", window.transform);
                InitializeRenderer(limitBar, defaultMaterial, colorID, memoryLimitColor);
                limitBar.transform.localScale    = new Vector3(0.99f, 0.2f, 1.0f);
                limitBar.transform.localPosition = new Vector3(0.0f, -0.37f, 0.0f);

                {
                    usedAnchor = CreateAnchor("UsedAnchor", limitBar.transform);
                    GameObject bar      = CreateQuad("UsedBar", usedAnchor);
                    Material   material = new Material(foregroundMaterial);
                    material.renderQueue = material.renderQueue + 1;
                    InitializeRenderer(bar, material, colorID, memoryUsedColor);
                    bar.transform.localScale    = Vector3.one;
                    bar.transform.localPosition = new Vector3(0.5f, 0.0f, 0.0f);
                }
                {
                    peakAnchor = CreateAnchor("PeakAnchor", limitBar.transform);
                    GameObject bar = CreateQuad("PeakBar", peakAnchor);
                    InitializeRenderer(bar, foregroundMaterial, colorID, memoryPeakColor);
                    bar.transform.localScale    = Vector3.one;
                    bar.transform.localPosition = new Vector3(0.5f, 0.0f, 0.0f);
                }
            }

            window.SetActive(isVisible);
        }
 public static void SetupColors()
 {
     flashingMaterial = new MaterialPropertyBlock();
     flashingMaterial.SetColor("_Color", UnityEngine.Color.magenta);
     ColorTranslationUtil.PopulateMaterialPropertyBlockMap(out materialPropertyBlocks);
 }
Esempio n. 4
0
        public void DrawLine(ref int startX, ref int startY, ref int endX, ref int endY)
        {
            if (mIsDispose)
            {
                return;
            }

            var p0       = new Vector2(startX, mCanvasSize.y - startY);
            var p1       = new Vector2(endX, mCanvasSize.y - endY);
            var distance = Vector2.Distance(p0, p1);
            var degree   = Vector2.SignedAngle(cVectorRight, p1 - p0);

            cBlock.Clear();
            cBlock.SetColor(cShaderPropColor, mColor);

            var matrix   = calcMatrix(mCountDraw++, startX, startY, distance, 1f, degree);
            var hasAlpha = (mColor.a > 0f);
            var buffer   = hasAlpha ? cBufferTransparent : cBufferOpaque;
            var material = hasAlpha ? cMaterialTransparentColor : cMaterialOpaque;

            buffer.DrawMesh(cMeshRect, matrix, material, 0, -1, cBlock);
        }
 public static MaterialPropertyBlock Property(this MaterialPropertyBlock m, string name, Color color)
 {
     m.SetColor(name, color);
     return(m);
 }
    private void Update()
    {
        float dt = Time.deltaTime;

        float[] samples = new float[waveSamples];//[16384];
        audioSource.GetOutputData(samples, 0);
        float sum = samples[0] + samples[samples.Length - 1];

        for (int i = 9; i < samples.Length; ++i)
        {
            waveFormRenderer.SetPosition(i, new Vector3(i, samples[i] * 1000f, 0f));
            //sum += Mathf.Abs(samples[i]);
            //Debug.DrawLine(new Vector3(i - 1, samples[i] * 1000f, 0f), new Vector3(i, samples[i + 1] * 1000f, 0f), Color.cyan);
        }

        sum /= samples.Length;
        if (sum > maxRecordedSum)
        {
            maxRecordedSum = sum;
        }

        if (volumeColorer != null)
        {
            MaterialPropertyBlock block = new MaterialPropertyBlock();
            Color c = Color.Lerp(minColor, maxColor, Mathf.InverseLerp(0f, maxRecordedSum, sum));
            block.SetColor("_Color", c);
            volumeColorer.SetPropertyBlock(block);
            RenderSettings.skybox.SetColor("_Tint", c);
            waveFormRenderer.startColor = c;
            waveFormRenderer.endColor   = c;
        }


        //float[] spectrum = new float[64];

        AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);

        StartCoroutine(Visualize());

        //for(int i = 0; i < spectrumSamples; ++i)
        //{
        //    //Debug.Log(-Mathf.Log(spectrum[i], 2f));
        //    if (spectrum[i] > spectrumMax[i])
        //        spectrumMax[i] = spectrum[i];
        //
        //    spectrumSum[i] /= 2f;
        //    spectrumSum[i] += spectrum[i];
        //    vis[i].localScale = new Vector3(1f, Mathf.Lerp(0f, visHeight, Mathf.InverseLerp(0f, spectrumMax[i], spectrumSum[i])), 1f);
        //    //vis[i].localScale = new Vector3(1f, Mathf.Lerp(0f, visHeight, Mathf.InverseLerp(0f, spectrumMax[i], spectrum[i])), 1f);
        //    vis[i].position = new Vector3(i, vis[i].localScale.y / 2f, 0f);
        //}

        //for (int i = 1; i < spectrum.Length - 1; i++)
        //{
        //    Debug.DrawLine(new Vector3(i - 1, Mathf.Log(spectrum[i], 2f), 0f), new Vector3(i, Mathf.Log(spectrum[i + 1], 2f), 0f), Color.cyan);
        //    //Debug.DrawLine(new Vector3(i - 1, spectrum[i] + 10, 0), new Vector3(i, spectrum[i + 1] + 10, 0), Color.red);
        //    //Debug.DrawLine(new Vector3(i - 1, Mathf.Log(spectrum[i - 1]) + 10, 2), new Vector3(i, Mathf.Log(spectrum[i]) + 10, 2), Color.cyan);
        //    //Debug.DrawLine(new Vector3(Mathf.Log(i - 1), spectrum[i - 1] - 10, 1), new Vector3(Mathf.Log(i), spectrum[i] - 10, 1), Color.green);
        //    //Debug.DrawLine(new Vector3(Mathf.Log(i - 1), Mathf.Log(spectrum[i - 1]), 3), new Vector3(Mathf.Log(i), Mathf.Log(spectrum[i]), 3), Color.blue);
        //}
    }
Esempio n. 7
0
 void Start()
 {
     activeCircle = new MaterialPropertyBlock();
     activeCircle.SetColor("_TintColor", Color.red);
 }
Esempio n. 8
0
 public void UpdateColor(MaterialPropertyBlock p)
 {
     p.SetColor("_Primary_Color", GetColor());
     p.SetColor("_Secondary_Color", GetSecondaryColor());
 }
Esempio n. 9
0
 public void SetColor(MaterialPropertyBlock block, Color color)
 {
     block.SetColor(ColorID, color);
 }
Esempio n. 10
0
 public void SetColor(Color color)
 {
     meshRenderer.enabled = (color.a > float.Epsilon);
     propertyBlock.SetColor(colorPropId, color);
     meshRenderer.SetPropertyBlock(propertyBlock);
 }
Esempio n. 11
0
 private void Awake()
 {
     block = new MaterialPropertyBlock();
     block.SetColor("_Color", Color.blue);
     //GetComponent<ParticleSystem>().GetComponent<Renderer>().materi
 }
Esempio n. 12
0
 public static void SetEmission(this Renderer renderer, Color color)
 {
     renderer.GetPropertyBlock(propertyBlock);
     propertyBlock.SetColor(ShaderConsts.EmissionID, color);
     renderer.SetPropertyBlock(propertyBlock);
 }
Esempio n. 13
0
    void SetShaderPropertiesBlock(MaterialPropertyBlock propertyBlock)
    {
        propertyBlock.SetVector(_idNoiseOffset, _angle);
        propertyBlock.SetVector(_idMinBounds, _minBounds);
        propertyBlock.SetVector(_idMaxBounds, _maxBounds);
        propertyBlock.SetMatrix(_idProjection, _projectionMatrixCached);
        propertyBlock.SetMatrix(_idViewWorldLight, _viewWorldLight);
        propertyBlock.SetMatrix(_idLocalRotation, _localRotation);
        propertyBlock.SetMatrix(_idRotation, _rotation);
        propertyBlock.SetColor(_idColorTint, colorTint);
        propertyBlock.SetFloat(_idLightMultiplier, lightMultiplier);
        propertyBlock.SetVector("_WorldPos", (CachedTransform.position + CachedTransform.forward) * worldScrollAmount);

        var lightMaterial = LightMaterial;

        if (useSoftBlend)
        {
            lightMaterial.EnableKeyword("_SOFTBLEND_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_SOFTBLEND_ON");
        }

        if (useDithering)
        {
            propertyBlock.SetFloat(_idJitterAmount, ditherAmount);
            propertyBlock.SetTexture(_idDitherTex, DitherTexture);
            lightMaterial.EnableKeyword("_DITHER_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_DITHER_ON");
        }

        if (useCurves)
        {
            propertyBlock.SetTexture(_idFallOffTex, FallOffTexture);
            lightMaterial.EnableKeyword("_CURVE_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_CURVE_ON");
        }

        switch (lightType)
        {
        case LightTypes.Point:
        case LightTypes.Spot:
        case LightTypes.Orthographic:
            propertyBlock.SetFloat(_idSpotExponent, spotExponent);
            propertyBlock.SetFloat(_idConstantAttenuation, constantAttenuation);
            propertyBlock.SetFloat(_idLinearAttenuation, linearAttenuation);
            propertyBlock.SetFloat(_idQuadraticAttenuation, quadraticAttenuation);
            break;

        case LightTypes.Area:
            Vector4 p = volumeTextureOffset;
            p.w = volumeTextureScale;
            propertyBlock.SetVector(_idVolumeOffset, p);
            propertyBlock.SetFloat(_idVolumeParams, shapeValue);
            switch (volumeShape)
            {
            case VolumeShape.Cube:
                lightMaterial.EnableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.Sphere:
                lightMaterial.EnableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.RoundedCube:
                lightMaterial.EnableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.Cylinder:
                lightMaterial.EnableKeyword("_SHAPE_CYLINDER");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                break;
            }
            break;
        }

        switch (lightType)
        {
        case LightTypes.Area:
            propertyBlock.SetTexture("_MainTex", areaVolume != null ? areaVolume : EmptyTexture3D);
            break;

        case LightTypes.Point:
            propertyBlock.SetTexture("_LightColorEmission", pointEmission != null ? pointEmission : EmptyCubemap);
            propertyBlock.SetTexture("_NoiseTex", pointNoise != null ? pointNoise : EmptyCubemap);
            propertyBlock.SetTexture("_ShadowTexture", pointShadow != null ? pointShadow : EmptyCubemap);
            break;

        case LightTypes.Spot:
        case LightTypes.Orthographic:
            propertyBlock.SetTexture("_LightColorEmission", spotEmission != null ? spotEmission : EmptyTexture2D);
            propertyBlock.SetTexture("_NoiseTex", spotNoise != null ? spotNoise : EmptyTexture2D);
            propertyBlock.SetTexture("_ShadowTexture", spotShadow != null ? spotShadow : EmptyTexture2D);
            break;
        }

        var shouldUseCustomShadowMap = false;

        cam.targetTexture = null;
        switch (shadowMode)
        {
        case ShadowMode.Realtime:
            if (_depthTexture == null)
            {
                CreateDepthTexture(lightType);
            }
            propertyBlock.SetTexture("_ShadowTexture", _depthTexture);
            lightMaterial.EnableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = renderFullShadows;
            break;

        case ShadowMode.Baked:
            lightMaterial.EnableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = false;
            break;

        case ShadowMode.None:
            lightMaterial.DisableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = false;
            break;
        }

        if (shouldUseCustomShadowMap)
        {
            lightMaterial.EnableKeyword("_SHADOW_EXP");
        }
        else
        {
            lightMaterial.DisableKeyword("_SHADOW_EXP");
        }

        float far  = cam.farClipPlane;
        float near = cam.nearClipPlane;
        float fov  = cam.fieldOfView;

        far  = spotRange;
        near = Mathf.Max(0.01f, spotNear);
        fov  = spotAngle;

        cam.farClipPlane = far;

        if (lightType == LightTypes.Point || lightType == LightTypes.Area)
        {
            near = -pointLightRadius;
            far  = pointLightRadius;
        }

        switch ((lightType))
        {
        case LightTypes.Point:
        case LightTypes.Area:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, pointLightRadius));
            break;

        case LightTypes.Orthographic:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, orthoSize));
            break;

        default:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, fov * 0.5f * Mathf.Deg2Rad));
            break;
        }
    }
Esempio n. 14
0
 private void UpdateColor(Color color)
 {
     _renderer.GetPropertyBlock(_propBlock);
     _propBlock.SetColor("_color", color);
     _renderer.SetPropertyBlock(_propBlock);
 }
Esempio n. 15
0
        public void SetResolution(int width, int height)
        {
            mCanvasSize = new Vector2(width, height);

            mBoxViewport = new Box(
                cCamera.ViewportToWorldPoint(new Vector3(0, 0, cCamera.nearClipPlane)),
                cCamera.ViewportToWorldPoint(new Vector3(1, 1, cCamera.farClipPlane))
                );

            var canvasAspect   = mCanvasSize.x / mCanvasSize.y;
            var viewportAspect = mBoxViewport.Width / mBoxViewport.Height;

            if (canvasAspect < viewportAspect)
            {
                // 左右に黒帯
                mBoxCanvas = new Box(
                    mBoxViewport.MinY * canvasAspect, mBoxViewport.MinY, mBoxViewport.MinZ,
                    mBoxViewport.MaxY * canvasAspect, mBoxViewport.MaxY, mBoxViewport.MaxZ
                    );
            }
            else if (canvasAspect > viewportAspect)
            {
                // 上下に黒帯
                mBoxCanvas = new Box(
                    mBoxViewport.MinX, mBoxViewport.MinX / canvasAspect, mBoxViewport.MinZ,
                    mBoxViewport.MaxX, mBoxViewport.MaxX / canvasAspect, mBoxViewport.MaxZ
                    );
            }
            else
            {
                // 黒帯なし
                mBoxCanvas = mBoxViewport;
            }

            var screenMin = cCamera.WorldToScreenPoint(new Vector3(mBoxCanvas.MinX, mBoxCanvas.MinY));
            var screenMax = cCamera.WorldToScreenPoint(new Vector3(mBoxCanvas.MaxX, mBoxCanvas.MaxY));

            mRectScreen = new Rect(screenMin, screenMax - screenMin);

            mMatrixView   = Matrix4x4.TRS(new Vector3(-1f, -1f, 0f), Quaternion.identity, new Vector3(2f / mCanvasSize.x, 2f / mCanvasSize.y, 1f));
            mMatrixProj   = Matrix4x4.Ortho(-1f, 1f, -1f, 1f, -100f, 0f);
            mPixelSizeMin = Mathf.Max(1f, mCanvasSize.x / mRectScreen.width);

            if (mPrevFrame == null || mPrevFrame.width != mScreenSize.x || mPrevFrame.height != mScreenSize.y)
            {
                mPrevFrame?.Release();
                mPrevFrame      = new RenderTexture(mScreenSize.x, mScreenSize.y, 0, UnityEngine.Experimental.Rendering.DefaultFormat.LDR);
                mPrevFrame.name = "PrevFrame";
                mPrevFrame.Create();
                Graphics.SetRenderTarget(mPrevFrame);
                {
                    cBlock.Clear();
                    cBlock.SetColor(cShaderPropColor, cColorWhite);
                    var t      = new Vector3(mBoxCanvas.MinX, mBoxCanvas.MaxY, 0f);
                    var s      = new Vector3(mBoxCanvas.Width, mBoxCanvas.Height, 1f);
                    var matrix = Matrix4x4.TRS(t, Quaternion.identity, s);
                    Graphics.DrawMesh(cMeshRect, matrix, cMaterialOpaque, 0, cCamera, 0, cBlock);
                }
                Graphics.SetRenderTarget(null);
            }
        }
Esempio n. 16
0
        private void UpdateHead()
        {
            if (!IsHead)
            {
                EnableHead = false;
                return;
            }

            int currentTiming = ArcGameplayManager.Instance.Timing;
            int offset        = ArcAudioManager.Instance.AudioOffset;

            if (arc.Position > 100000 || arc.Position < -10000)
            {
                EnableHead = false;
                return;
            }
            EnableHead = true;
            if (arc.Position > 90000 && arc.Position <= 100000)
            {
                Head.localPosition          = new Vector3();
                HeadRenderer.sharedMaterial = arcMaterial;
                Color highC = currentHighColor;
                highC.a = currentHighColor.a * (100000 - arc.Position) / 100000;
                Color lowC = currentLowColor;
                lowC.a = currentLowColor.a * (100000 - arc.Position) / 100000;
                HeadRenderer.GetPropertyBlock(headPropertyBlock);
                headPropertyBlock.SetColor(highColorShaderId, highC);
                headPropertyBlock.SetColor(lowColorShaderId, lowC);
                HeadRenderer.SetPropertyBlock(headPropertyBlock);
            }
            else if (arc.Timing + offset < currentTiming)
            {
                HeadRenderer.GetPropertyBlock(headPropertyBlock);
                headPropertyBlock.SetColor(highColorShaderId, currentHighColor);
                headPropertyBlock.SetColor(lowColorShaderId, currentLowColor);
                HeadRenderer.SetPropertyBlock(headPropertyBlock);
                if (arc.Judging || arc.IsVoid)
                {
                    if (segmentCount >= 1)
                    {
                        ArcArcSegmentComponent s = segments[0];
                        int   duration           = s.ToTiming - s.FromTiming;
                        float t = duration == 0 ? 0 : ((-arc.Position / 1000f) / (-s.ToPos.z));
                        if (t > 1)
                        {
                            EnableHead = false;
                            return;
                        }
                        else if (t < 0)
                        {
                            t = 0;
                        }
                        Head.localPosition = (s.ToPos - s.FromPos) * t;
                    }
                }
                else
                {
                    Head.localPosition = new Vector3();
                }
            }
            else
            {
                HeadRenderer.GetPropertyBlock(headPropertyBlock);
                headPropertyBlock.SetColor(highColorShaderId, currentHighColor);
                headPropertyBlock.SetColor(lowColorShaderId, currentLowColor);
                HeadRenderer.SetPropertyBlock(headPropertyBlock);
                Head.localPosition = new Vector3();
            }
        }
Esempio n. 17
0
 // Update is called once per frame
 void Update()
 {
     props.SetColor("_Color", color);
     props.SetFloat("_AnimationSpeed", animationSpeed);
     mrenderer.SetPropertyBlock(props);
 }
Esempio n. 18
0
 private void ChangeColor(Color c)
 {
     block.SetColor("_Color", c);
     myMesh.SetPropertyBlock(block);
 }
Esempio n. 19
0
    public void Draw(IMDrawCamera component)
    {
        s_MaterialPropertyBlock.SetColor(IMDrawSPID._Color, m_Color);
        //s_MaterialPropertyBlock.SetFloat(IMDrawSPID._ZTest, (float)m_ZTest); // This doesn't work for some reason - probably a Unity bug?
        component.MaterialMesh.SetInt(IMDrawSPID._ZTest, (int)m_ZTest);

        switch (m_Type)
        {
        case IMDrawCommandType.QUAD:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshQuad, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.BOX:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshBox, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.PYRAMID:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshPyramid, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.RHOMBUS:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshRhombus, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.ARC:
        {
            DrawArc(component);
        }
        break;

        case IMDrawCommandType.DISC:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshDisc, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.SPHERE:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshSphere, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.CONE:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshCone, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.CAPSULE:
        {
            float bodyHeight = m_Size.y - (m_Size.x * 2f);

            if (bodyHeight > 0f)
            {
                s_Matrix.SetTRS(m_Position, m_Rotation, new Vector3(m_Size.x, bodyHeight, m_Size.z));
                Graphics.DrawMesh(IMDrawManager.Instance.MeshCapsuleBody, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
            }

            Vector3 capOffset = ToUpVector(bodyHeight * 0.5f);

            s_Matrix.SetTRS(
                m_Position + capOffset,
                m_Rotation,
                new Vector3(m_Size.x, m_Size.x, m_Size.x));
            Graphics.DrawMesh(IMDrawManager.Instance.MeshCapsuleCap, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);

            s_Matrix.SetTRS(
                m_Position - capOffset,
                m_Rotation * CAPSULE_BOTTOM_CAP_ROTATION,
                new Vector3(m_Size.x, m_Size.x, m_Size.x));

            Graphics.DrawMesh(IMDrawManager.Instance.MeshCapsuleCap, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.CYLINDER:
        {
            s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
            Graphics.DrawMesh(IMDrawManager.Instance.MeshCylinder, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
        }
        break;

        case IMDrawCommandType.CUSTOM_MESH:
        {
            if (m_Mesh != null)
            {
                s_Matrix.SetTRS(m_Position, m_Rotation, m_Size);
                Graphics.DrawMesh(m_Mesh, s_Matrix, component.MaterialMesh, component.MeshLayer, component.Camera, 0, s_MaterialPropertyBlock);
            }
        }
        break;
        }
    }
Esempio n. 20
0
 static TeamColors()
 {
     friendly.SetColor("_Color", Color.green);
     enemy.SetColor("_Color", Color.red);
 }
Esempio n. 21
0
        private void CreateInstancedProbes()
        {
            foreach (var cell in ProbeReferenceVolume.instance.cells.Values)
            {
                if (cell.sh == null || cell.sh.Length == 0)
                {
                    continue;
                }

                float largestBrickSize = cell.bricks.Count == 0 ? 0 : cell.bricks[0].size;

                List <Matrix4x4[]>           probeBuffers = new List <Matrix4x4[]>();
                List <MaterialPropertyBlock> props        = new List <MaterialPropertyBlock>();
                List <int[]> probeMaps = new List <int[]>();

                // Batch probes for instanced rendering
                for (int brickSize = 0; brickSize < largestBrickSize + 1; brickSize++)
                {
                    List <Matrix4x4> probeBuffer = new List <Matrix4x4>();
                    List <int>       probeMap    = new List <int>();

                    for (int i = 0; i < cell.probePositions.Length; i++)
                    {
                        // Skip probes which aren't of current brick size
                        if (cell.bricks[i / 64].size == brickSize)
                        {
                            probeBuffer.Add(Matrix4x4.TRS(cell.probePositions[i], Quaternion.identity, Vector3.one * (0.3f * (brickSize + 1))));
                            probeMap.Add(i);
                        }

                        // Batch limit reached or out of probes
                        if (probeBuffer.Count >= probesPerBatch || i == cell.probePositions.Length - 1)
                        {
                            MaterialPropertyBlock prop = new MaterialPropertyBlock();
                            float gradient             = largestBrickSize == 0 ? 1 : brickSize / largestBrickSize;
                            prop.SetColor("_Color", Color.Lerp(Color.red, Color.green, gradient));
                            props.Add(prop);

                            probeBuffers.Add(probeBuffer.ToArray());
                            probeBuffer = new List <Matrix4x4>();
                            probeMaps.Add(probeMap.ToArray());
                            probeMap = new List <int>();
                        }
                    }
                }

                var debugData = new CellInstancedDebugProbes();
                debugData.probeBuffers = probeBuffers;
                debugData.props        = props;
                debugData.probeMaps    = probeMaps;
                debugData.cellPosition = cell.position;

                Vector4[][] shBuffer = new Vector4[4][];
                for (int i = 0; i < shBuffer.Length; i++)
                {
                    shBuffer[i] = new Vector4[probesPerBatch];
                }

                Vector4[] validityColors = new Vector4[probesPerBatch];

                for (int batchIndex = 0; batchIndex < debugData.probeMaps.Count; batchIndex++)
                {
                    for (int indexInBatch = 0; indexInBatch < debugData.probeMaps[batchIndex].Length; indexInBatch++)
                    {
                        int probeIdx = debugData.probeMaps[batchIndex][indexInBatch];

                        shBuffer[0][indexInBatch] = new Vector4(cell.sh[probeIdx][0, 3], cell.sh[probeIdx][0, 1], cell.sh[probeIdx][0, 2], cell.sh[probeIdx][0, 0]);
                        shBuffer[1][indexInBatch] = new Vector4(cell.sh[probeIdx][1, 3], cell.sh[probeIdx][1, 1], cell.sh[probeIdx][1, 2], cell.sh[probeIdx][1, 0]);
                        shBuffer[2][indexInBatch] = new Vector4(cell.sh[probeIdx][2, 3], cell.sh[probeIdx][2, 1], cell.sh[probeIdx][2, 2], cell.sh[probeIdx][2, 0]);

                        validityColors[indexInBatch] = Color.Lerp(Color.green, Color.red, cell.validity[probeIdx]);
                    }

                    debugData.props[batchIndex].SetVectorArray("_R", shBuffer[0]);
                    debugData.props[batchIndex].SetVectorArray("_G", shBuffer[1]);
                    debugData.props[batchIndex].SetVectorArray("_B", shBuffer[2]);

                    debugData.props[batchIndex].SetVectorArray("_Validity", validityColors);
                }

                cellDebugData.Add(debugData);
            }
        }
    void Update()
    {
        if (CachedBlock == null)
        {
            CachedBlock = new MaterialPropertyBlock();
        }

        var curIndex = 0;

        foreach (var mn in Meshes)
        {
            curIndex++;

            // Increment time for this mesh.
            if (CycleTime == 0.0f)
            {
                continue;
            }
#if UNITY_EDITOR
            mn.Time = Mathf.Repeat(mn.Time + (float)editorDeltaTime * mn.SpeedScale, 1.0f);
            if (this == null)
            {
                UnityEditor.EditorApplication.update -= EditorUpdate;
                return;
            }
#else
            mn.Time = Mathf.Repeat(mn.Time + Time.deltaTime * mn.SpeedScale, 1.0f);
#endif
            var t = mn.Time;

            // Apply state.
            var mt = mn.MeshGO.transform;

            var  offset         = Vector3.zero;
            bool applyAnimation = true;

            if (SpawnOnGrid)
            {
                int xIdx, yIdx, zIdx;
                ConvertIndexToGridIndex(curIndex, out xIdx, out yIdx, out zIdx);

                offset = ConvertGridIndexToLocalPosition(xIdx, yIdx, zIdx);

                if (EnableGridMotionLock)
                {
                    applyAnimation = CheckGridItemMotionLock(applyAnimation, xIdx, yIdx, zIdx);
                }
            }

            var animationOffset = DirectionOfMotion * Location.Evaluate(t);

            if (!applyAnimation)
            {
                animationOffset = Vector3.zero;
            }

            mt.localPosition = offset + animationOffset;

            mt.localScale    = Scale.Evaluate(t) * ScaleFactor;
            mt.localRotation = Quaternion.AngleAxis(Rotation.Evaluate(t) * RotationScale, AxisOfRotation);

            // For color use a material property block to be instance compatible.
            var mr = mn.MeshGO.GetComponent <MeshRenderer>();

            // Note clever gamma math. Apparently the particle system does this
            // silently, but now we match it!
            var tmp = Color.Evaluate(t);
            var bt  = BaseTint.linear;

            tmp.r *= bt.r;
            tmp.g *= bt.g;
            tmp.b *= bt.b;
            tmp.a *= bt.a;

            mr.GetPropertyBlock(CachedBlock);
            CachedBlock.SetColor("_TintColor", tmp.gamma);
            mr.SetPropertyBlock(CachedBlock);
        }
    }
Esempio n. 23
0
    // Start is called before the first frame update
    void Start()
    {
        print(SystemInfo.graphicsDeviceName);
        // Infro from C# (CPU) into the Shader (GPU)
        MaterialPropertyBlock props = new MaterialPropertyBlock();
        MeshRenderer          renderer;

        for (int i = 0; i < instances; i++)
        {
            Transform d1 = Instantiate(cable);
            Transform d2 = Instantiate(brokenPanel);
            Transform d3 = Instantiate(capsule);
            Transform d4 = Instantiate(halfCapsule);
            Transform d5 = Instantiate(antenna);

            //first debris type
            d1.localPosition = Random.insideUnitSphere * radius;
            d1.rotation      = Random.rotation;
            d1.SetParent(transform);

            float r = Random.Range(0.0f, 1.0f);
            float g = r;
            float b = r;

            float x = Random.Range(0.8f, 2.0f);
            float y = Random.Range(0.8f, 2.0f);
            float z = Random.Range(0.8f, 2.0f);

            d1.localScale += new Vector3(x, y, z);

            props.SetColor("_Color", new Color(r, g, b));

            renderer = d1.GetComponent <MeshRenderer>();
            renderer.SetPropertyBlock(props);

            //second debris type
            d2.localPosition = Random.insideUnitSphere * radius;
            d2.rotation      = Random.rotation;
            d2.SetParent(transform);

            x = Random.Range(0.8f, 2.0f);
            y = Random.Range(0.8f, 2.0f);
            z = Random.Range(0.8f, 2.0f);

            d2.localScale += new Vector3(x, y, z);

            renderer = d2.GetComponent <MeshRenderer>();
            renderer.SetPropertyBlock(props);

            //third debris type
            d3.localPosition = Random.insideUnitSphere * radius;
            d3.rotation      = Random.rotation;
            d3.SetParent(transform);

            x = Random.Range(0.8f, 2.0f);
            y = Random.Range(0.8f, 2.0f);
            z = Random.Range(0.8f, 2.0f);

            d3.localScale += new Vector3(x, y, z);

            renderer = d3.GetComponent <MeshRenderer>();
            renderer.SetPropertyBlock(props);

            //fourth debris type
            d4.localPosition = Random.insideUnitSphere * radius;
            d4.rotation      = Random.rotation;
            d4.SetParent(transform);

            x = Random.Range(0.8f, 2.0f);
            y = Random.Range(0.8f, 2.0f);
            z = Random.Range(0.8f, 2.0f);

            d4.localScale += new Vector3(x, y, z);

            renderer = d4.GetComponent <MeshRenderer>();
            renderer.SetPropertyBlock(props);

            //fifth debris type
            d5.localPosition = Random.insideUnitSphere * radius;
            d5.rotation      = Random.rotation;
            d5.SetParent(transform);

            x = Random.Range(0.8f, 2.0f);
            y = Random.Range(0.8f, 2.0f);
            z = Random.Range(0.8f, 2.0f);

            d5.localScale += new Vector3(x, y, z);

            renderer = d5.GetComponent <MeshRenderer>();
            renderer.SetPropertyBlock(props);
        }
    }
Esempio n. 24
0
    public void GenNewShape()
    {
        MaterialPropertyBlock props = new MaterialPropertyBlock();

        for (int i = 0; i < countmax; i++)
        {
            if (i < count)
            {
                //MATERIAL

                //Random grey color
                if (greyScale)
                {
                    float grey = Random.Range(randomGreyRange.x, randomGreyRange.y);
                    props.SetColor("_BaseColor", new Color(grey, grey, grey));
                }
                else
                {
                    props.SetColor("_BaseColor", Color.black);
                }

                //Random texture
                int tid = Random.Range(0, texture_shapes.Length);
                props.SetTexture("_BaseMap", (Texture2D)texture_shapes[tid]);

                //Random cutoff
                float cutoff = Random.Range(0.1f, 1.0f);
                props.SetFloat("_Cutoff", cutoff);

                //Assign to MaterialPropertyBlock
                renderers[i].SetPropertyBlock(props);

                // TRANSFORM

                //Random position
                if (posCenter)
                {
                    renderers[i].transform.localPosition = CommonTools.RandomV3(Vector3.one * randomPosition * -i, Vector3.one * randomPosition * i);
                }
                else
                {
                    renderers[i].transform.localPosition = CommonTools.RandomV3(-Vector3.one * randomPosition, Vector3.one * randomPosition);
                }


                //Random rotation
                Vector3 rot = CommonTools.RandomV3(Vector3.zero, Vector3.one * 360.0f);
                renderers[i].transform.localRotation = Quaternion.Euler(rot.x, rot.y, rot.z);

                //Random scale
                renderers[i].transform.localScale = CommonTools.RandomV3(Vector3.one * randomScaRange.x, Vector3.one * randomScaRange.y);

                //Make sure Renderer is enabled
                renderers[i].enabled = true;
            }
            else
            {
                renderers[i].enabled = false;
            }
        }
    }
Esempio n. 25
0
        public void RenderVehicle(VehicleInfo info, Color color, bool useColor = true)
        {
            InfoManager instance = Singleton <InfoManager> .instance;

            InfoManager.InfoMode    currentMode    = instance.CurrentMode;
            InfoManager.SubInfoMode currentSubMode = instance.CurrentSubMode;
            instance.SetCurrentMode(InfoManager.InfoMode.None, InfoManager.SubInfoMode.Default);
            instance.UpdateInfoMode();
            Light   sunLightSource = DayNightProperties.instance.sunLightSource;
            float   intensity      = sunLightSource.intensity;
            Color   color2         = sunLightSource.color;
            Vector3 eulerAngles    = sunLightSource.transform.eulerAngles;

            sunLightSource.intensity             = 2f;
            sunLightSource.color                 = Color.white;
            sunLightSource.transform.eulerAngles = new Vector3(50f, 180f, 70f);
            Light mainLight = Singleton <RenderManager> .instance.MainLight;

            Singleton <RenderManager> .instance.MainLight = sunLightSource;
            if (mainLight == DayNightProperties.instance.moonLightSource)
            {
                DayNightProperties.instance.sunLightSource.enabled  = true;
                DayNightProperties.instance.moonLightSource.enabled = false;
            }
            Vector3 one       = Vector3.one;
            float   magnitude = info.m_mesh.bounds.extents.magnitude;
            float   num       = magnitude + 16f;
            float   num2      = magnitude * this.m_zoom;

            this.m_camera.transform.position = Vector3.forward * num2;
            this.m_camera.transform.rotation = Quaternion.AngleAxis(180f, Vector3.up);
            this.m_camera.nearClipPlane      = Mathf.Max(num2 - num * 1.5f, 0.01f);
            this.m_camera.farClipPlane       = num2 + num * 1.5f;
            Quaternion            quaternion    = Quaternion.Euler(20f, 0f, 0f) * Quaternion.Euler(0f, this.m_rotation, 0f);
            Vector3               pos           = quaternion * -info.m_mesh.bounds.center;
            Vector3               arg_1CC_0     = Vector3.zero;
            VehicleManager        instance2     = Singleton <VehicleManager> .instance;
            Matrix4x4             matrix        = Matrix4x4.TRS(pos, quaternion, Vector3.one);
            Matrix4x4             value         = info.m_vehicleAI.CalculateTyreMatrix(Vehicle.Flags.Created, ref pos, ref quaternion, ref one, ref matrix);
            MaterialPropertyBlock materialBlock = instance2.m_materialBlock;

            materialBlock.Clear();
            materialBlock.SetMatrix(instance2.ID_TyreMatrix, value);
            materialBlock.SetVector(instance2.ID_TyrePosition, Vector3.zero);
            materialBlock.SetVector(instance2.ID_LightState, Vector3.zero);
            if (useColor)
            {
                materialBlock.SetColor(instance2.ID_Color, color);
            }
            instance2.m_drawCallData.m_defaultCalls = instance2.m_drawCallData.m_defaultCalls + 1;
            info.m_material.SetVectorArray(instance2.ID_TyreLocation, info.m_generatedInfo.m_tyres);
            Graphics.DrawMesh(info.m_mesh, matrix, info.m_material, 0, this.m_camera, 0, materialBlock, true, true);
            this.m_camera.RenderWithShader(info.m_material.shader, "");
            sunLightSource.intensity                      = intensity;
            sunLightSource.color                          = color2;
            sunLightSource.transform.eulerAngles          = eulerAngles;
            Singleton <RenderManager> .instance.MainLight = mainLight;
            if (mainLight == DayNightProperties.instance.moonLightSource)
            {
                DayNightProperties.instance.sunLightSource.enabled  = false;
                DayNightProperties.instance.moonLightSource.enabled = true;
            }
            instance.SetCurrentMode(currentMode, currentSubMode);
            instance.UpdateInfoMode();
        }
 public PropertyBlockProxy SetColor(string fieldName, Color value)
 {
     _propertyBlock.SetColor(fieldName, value);
     return(this);
 }
Esempio n. 27
0
 public void SetColor(Color c)
 {
     prop.SetColor(ShaderNameHash.TintColor, c);
     rendererCache.SetPropertyBlock(prop);
 }
Esempio n. 28
0
        public void RenderVehicle(VehicleInfo info, Color color, bool useColor = true)
        {
            InfoManager infoManager = Singleton <InfoManager> .instance;

            InfoManager.InfoMode    currentMod    = infoManager.CurrentMode;
            InfoManager.SubInfoMode currentSubMod = infoManager.CurrentSubMode;;
            infoManager.SetCurrentMode(InfoManager.InfoMode.None, InfoManager.SubInfoMode.Default);
            infoManager.UpdateInfoMode();

            Light   sunLight       = DayNightProperties.instance.sunLightSource;
            float   lightIntensity = sunLight.intensity;
            Color   lightColor     = sunLight.color;
            Vector3 lightAngles    = sunLight.transform.eulerAngles;

            sunLight.intensity             = 2f;
            sunLight.color                 = Color.white;
            sunLight.transform.eulerAngles = new Vector3(50, 180, 70);

            Light mainLight = RenderManager.instance.MainLight;

            RenderManager.instance.MainLight = sunLight;

            if (mainLight == DayNightProperties.instance.moonLightSource)
            {
                DayNightProperties.instance.sunLightSource.enabled  = true;
                DayNightProperties.instance.moonLightSource.enabled = false;
            }

            Vector3 one = Vector3.one;

            float magnitude = info.m_mesh.bounds.extents.magnitude;
            float num       = magnitude + 16f;
            float num2      = magnitude * m_zoom;

            m_camera.transform.position = Vector3.forward * num2;
            m_camera.transform.rotation = Quaternion.AngleAxis(180, Vector3.up);
            m_camera.nearClipPlane      = Mathf.Max(num2 - num * 1.5f, 0.01f);
            m_camera.farClipPlane       = num2 + num * 1.5f;

            Quaternion rotation = Quaternion.Euler(20f, 0f, 0f) * Quaternion.Euler(0f, m_rotation, 0f);
            Vector3    position = rotation * -info.m_mesh.bounds.center;

            // Vector3 swayPosition = Vector3.zero;        (commenting out, as never used)

            VehicleManager instance   = Singleton <VehicleManager> .instance;
            Matrix4x4      matrixBody = Matrix4x4.TRS(position, rotation, Vector3.one);
            Matrix4x4      matrixTyre = info.m_vehicleAI.CalculateTyreMatrix(Vehicle.Flags.Created, ref position, ref rotation, ref one, ref matrixBody);

            MaterialPropertyBlock materialBlock = instance.m_materialBlock;

            materialBlock.Clear();
            materialBlock.SetMatrix(instance.ID_TyreMatrix, matrixTyre);
            materialBlock.SetVector(instance.ID_TyrePosition, Vector3.zero);
            materialBlock.SetVector(instance.ID_LightState, Vector3.zero);
            if (useColor)
            {
                materialBlock.SetColor(instance.ID_Color, color);
            }

            instance.m_drawCallData.m_defaultCalls = instance.m_drawCallData.m_defaultCalls + 1;

            info.m_material.SetVectorArray(instance.ID_TyreLocation, info.m_generatedInfo.m_tyres);
            Graphics.DrawMesh(info.m_mesh, matrixBody, info.m_material, 0, m_camera, 0, materialBlock, true, true);

            m_camera.RenderWithShader(info.m_material.shader, "");

            sunLight.intensity             = lightIntensity;
            sunLight.color                 = lightColor;
            sunLight.transform.eulerAngles = lightAngles;

            RenderManager.instance.MainLight = mainLight;

            if (mainLight == DayNightProperties.instance.moonLightSource)
            {
                DayNightProperties.instance.sunLightSource.enabled  = false;
                DayNightProperties.instance.moonLightSource.enabled = true;
            }

            infoManager.SetCurrentMode(currentMod, currentSubMod);
            infoManager.UpdateInfoMode();
        }
Esempio n. 29
0
    void Start()
    {
        m_EnemyManager = FindObjectOfType <EnemyManager>();
        DebugUtility.HandleErrorIfNullFindObject <EnemyManager, EnemyController>(m_EnemyManager, this);

        m_ActorsManager = FindObjectOfType <ActorsManager>();
        DebugUtility.HandleErrorIfNullFindObject <ActorsManager, EnemyController>(m_ActorsManager, this);

        m_EnemyManager.RegisterEnemy(this);

        m_Health = GetComponent <Health>();
        DebugUtility.HandleErrorIfNullGetComponent <Health, EnemyController>(m_Health, this, gameObject);

        m_Actor = GetComponent <Actor>();
        DebugUtility.HandleErrorIfNullGetComponent <Actor, EnemyController>(m_Actor, this, gameObject);

        m_NavMeshAgent  = GetComponent <NavMeshAgent>();
        m_SelfColliders = GetComponentsInChildren <Collider>();

        m_GameFlowManager = FindObjectOfType <GameFlowManager>();
        DebugUtility.HandleErrorIfNullFindObject <GameFlowManager, EnemyController>(m_GameFlowManager, this);

        // Subscribe to damage & death actions
        m_Health.onDie     += OnDie;
        m_Health.onDamaged += OnDamaged;

        // Find and initialize all weapons
        FindAndInitializeAllWeapons();
        var weapon = GetCurrentWeapon();

        weapon.ShowWeapon(true);

        var detectionModules = GetComponentsInChildren <DetectionModule>();

        DebugUtility.HandleErrorIfNoComponentFound <DetectionModule, EnemyController>(detectionModules.Length, this, gameObject);
        DebugUtility.HandleWarningIfDuplicateObjects <DetectionModule, EnemyController>(detectionModules.Length, this, gameObject);
        // Initialize detection module
        m_DetectionModule = detectionModules[0];
        m_DetectionModule.onDetectedTarget += OnDetectedTarget;
        m_DetectionModule.onLostTarget     += OnLostTarget;
        onAttack += m_DetectionModule.OnAttack;

        var navigationModules = GetComponentsInChildren <NavigationModule>();

        DebugUtility.HandleWarningIfDuplicateObjects <DetectionModule, EnemyController>(detectionModules.Length, this, gameObject);
        // Override navmesh agent data
        if (navigationModules.Length > 0)
        {
            m_NavigationModule          = navigationModules[0];
            m_NavMeshAgent.speed        = m_NavigationModule.moveSpeed;
            m_NavMeshAgent.angularSpeed = m_NavigationModule.angularSpeed;
            m_NavMeshAgent.acceleration = m_NavigationModule.acceleration;
        }

        foreach (var renderer in GetComponentsInChildren <Renderer>(true))
        {
            for (int i = 0; i < renderer.sharedMaterials.Length; i++)
            {
                if (renderer.sharedMaterials[i] == eyeColorMaterial)
                {
                    m_EyeRendererData = new RendererIndexData(renderer, i);
                }

                if (renderer.sharedMaterials[i] == bodyMaterial)
                {
                    m_BodyRenderers.Add(new RendererIndexData(renderer, i));
                }
            }
        }

        m_BodyFlashMaterialPropertyBlock = new MaterialPropertyBlock();

        // Check if we have an eye renderer for this enemy
        if (m_EyeRendererData.renderer != null)
        {
            m_EyeColorMaterialPropertyBlock = new MaterialPropertyBlock();
            m_EyeColorMaterialPropertyBlock.SetColor("_EmissionColor", defaultEyeColor);
            m_EyeRendererData.renderer.SetPropertyBlock(m_EyeColorMaterialPropertyBlock, m_EyeRendererData.materialIndex);
        }
    }
Esempio n. 30
0
    internal void UpdateItems()
    {
        var heldItemIndex = inventory.FindLastIndex(x => x.item.mode == InventoryMode.Hauled || x.item.mode == InventoryMode.Weapon);

        if (heldItemIndex >= 0)
        {
            var heldItem = inventory[heldItemIndex];
            if (heldItem.item.item.type != heldItemType)
            {
                if (heldItemModel != null)
                {
                    Destroy(heldItemModel);
                }
                heldItemModel = ItemManager.InstantiateItem(heldItem.item.item, transform, false);
                heldItemModel.transform.localRotation = Quaternion.Euler(0, 0, -90);
            }
            else
            {
                if (heldItemModel != null)
                {
                    Destroy(heldItemModel);
                }
                heldItemModel = null;
            }
        }
        //Temporary fix until I get proper clothing meshes.
        foreach (var item in inventory)
        {
            if (item.item.mode != InventoryMode.Worn)
            {
                continue;
            }
            if (modeledPart != null)
            {
                if (modeledPart.Equipment.ContainsKey(item.item.item.type))
                {
                    var model = modeledPart.Equipment[item.item.item.type];
                    model.gameObject.SetActive(true);
                    model.UpdateMaterial(item.item.item);
                    continue;
                }
            }
            if (flags.head)
            {
                continue;
            }
            MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
            var color = ContentLoader.GetColor(item.item.item);
            var index = ContentLoader.GetPatternIndex(item.item.item.material);
            propertyBlock.SetColor("_MatColor", color);
            propertyBlock.SetFloat("_MatIndex", index);
            foreach (var layerModel in layerModels)
            {
                if (layerModel == null)
                {
                    continue;
                }
                var renderer = layerModel.GetComponentInChildren <MeshRenderer>();
                if (renderer != null)
                {
                    renderer.SetPropertyBlock(propertyBlock);
                }
            }
        }
    }