Here are the examples of the csharp api float.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
896 Examples
19
Source : UpdateTextWithSliderValue.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
private void UpdateText(float value)
{
m_text.text = value.ToString();
}
19
Source : G_FloatString.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
public static string ToStringNonAlloc(this float value)
{
int valIndex = value.ToIndex();
if (value < 0 && valIndex < negativeBuffer.Length)
{
return negativeBuffer[valIndex];
}
if (value >= 0 && valIndex < positiveBuffer.Length)
{
return positiveBuffer[valIndex];
}
return value.ToString();
}
19
Source : BlendshapePrinter.cs
with MIT License
from 734843327
with MIT License
from 734843327
void OnGUI()
{
if (shapeEnabled) {
string blendshapes = "";
string shapeNames = "";
string valueNames = "";
foreach(KeyValuePair<string,float> kvp in currentBlendShapes) {
blendshapes += " [";
blendshapes += kvp.Key.ToString ();
blendshapes += ":";
blendshapes += kvp.Value.ToString ();
blendshapes += "]\n";
shapeNames += "\"";
shapeNames += kvp.Key.ToString ();
shapeNames += "\",\n";
valueNames += kvp.Value.ToString ();
valueNames += "\n";
}
GUILayout.BeginHorizontal (GUILayout.ExpandHeight(true));
GUILayout.Box (blendshapes);
GUILayout.EndHorizontal ();
Debug.Log (shapeNames);
Debug.Log (valueNames);
}
}
19
Source : Inspector.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public void UpdateValue(int idx, float value)
{
var PropPanel = PropPanels[idx];
var slider = PropPanel.transform.Find("Slider").GetComponent<Slider>();
slider.value = value;
PropPanel.transform.Find("Value").GetComponent<InputField>().text = value.ToString();
}
19
Source : Inspector.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
internal UnityAction<float> UpdateTextDelegate(int idx)
{
var PropPanel = PropPanels[idx];
var slider = PropPanel.transform.Find("Slider").GetComponent<Slider>();
var text = PropPanel.transform.Find("Value").GetComponent<InputField>();
AddListener(idx, ((v) => {
text.text = v.ToString();
}));
text.onValueChanged.AddListener((va) =>
{
if (float.Parse(va) >= slider.minValue && float.Parse(va) <= slider.maxValue)
{
slider.value = float.Parse(va);
}
else
{
text.text = slider.minValue.ToString();
}
});
return null;
}
19
Source : CameraBodyEditorWindow.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private void DrawLensField () {
List<string> hfovList = new List<string>();
List<string> offsetList = new List<string>();
ProCamsLensDataTable.FilmFormatData curFilmFormat = ProCamsLensDataTable.Instance.GetFilmFormat(_ffList[_currentFilmFormatIndex]);
if(curFilmFormat != null)
{
ProCamsLensDataTable.LensKitData lensKit = curFilmFormat.GetLensKitData(_lensKitIndex);
if(lensKit != null)
{
if(_lensList == null)
{
_lensList = new string[lensKit._fovDataset.Count];
int i = 0;
foreach(ProCamsLensDataTable.FOVData fovData in lensKit._fovDataset)
{
_lensList[i] = fovData._focalLength + "mm";
++i;
}
}
foreach(ProCamsLensDataTable.FOVData fovData in lensKit._fovDataset)
{
//float hfov = Lens.GetHorizontalFOV(curFilmFormat._aspect, fovData._unityVFOV);
// Rounding to two decimal places
//hfov = Mathf.Floor(hfov * 100) / 100f;
//hfovList.Add ("" + hfov);
float hfov = Mathf.Floor(fovData._realHFOV * 100) / 100f;
hfovList.Add (hfov.ToString());
offsetList.Add ("" + fovData._nodalOffset);
}
}
}
_lensIndex = EditorGUILayout.Popup("Lenses", _lensIndex, _lensList);
//GUILayout.Space(20f);
DrawNodalPointOffsetField(offsetList[_lensIndex]);
DrawHFOVField(hfovList[_lensIndex]);
}
19
Source : DebugUISample.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public void SliderPressed(float f)
{
Debug.Log("Slider: " + f);
sliderText.text = f.ToString();
}
19
Source : VRSL_BPMCounter.cs
with MIT License
from AcChosen
with MIT License
from AcChosen
void BeatDetection()
{
text.text = "BPM: " + _bpm.ToString();
beatText.text = "Beat: " + _quarterNoteCount.ToString();
//replacedume there is no beat this frame
_beatFull = false;
//every second there will be a beat interval if bpm 60. a beat every half second at 120, etc. This sets what consireplacedutes what bpm is a "second". Default is 60.
_beatInterval = 60 / _bpm;
//increment timer every frame by however many seconds have preplaceded.
//_beatTimer += Time.fixedDeltaTime;
//_beatTimer += Time.fixedUnscaledDeltaTime;
_beatTimer += Time.deltaTime;
while (_beatTimer >= _beatInterval || manualStartBeat) // if it is time for a beat...
{
if(manualStartBeat)
{
_quarterNoteCount = 4;
manualStartBeat = false;
_beatInterval = 60 / _bpm;
_beatTimer += Time.deltaTime;
//setAnimSpeed();
}
_beatTimer -= _beatInterval; // subtract from the beat timer that interval that just preplaceded
_beatFull = true; //we are now on a beat
_beatCountFull++; //Increment the number of beats that have preplaceded.
if (_quarterNoteCount != 4)//Counting quarter notes!
{
_quarterNoteCount++;
}
else
{
// setAnimSpeed();
//DownBeat();
SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.All, "setAnimSpeed");
SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.All, "DownBeat");
}
// If this is a downbeat, save the server time when this occured (only the master uses this value)
if (captureNextDownbeat && _quarterNoteCount == 1)
{
captureNextDownbeat = false;
// lastDownbeatTimeSynced = Networking.GetServerTimeInSeconds();
}
}
//do the same but divide everything by 8 to get 1/8ths and 16ths.
_beatDivide8 = false;
_beatIntervalDivide8 = _beatInterval / 8;
_beatTimerDivide8 += Time.deltaTime;
if(_beatTimerDivide8 >= _beatIntervalDivide8)
{
_beatTimerDivide8 -= _beatIntervalDivide8;
_beatDivide8 = true;
if(_beatCountDivide8 != 8)
{
_beatCountDivide8++;
}
else
{
_beatCountDivide8 = 1;
}
}
}
19
Source : ConfigFile.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public void StoreValues()
{
foreach (var pair in booleans)
{
RefreshValue(pair.Key, pair.Value.ToString());
}
foreach (var pair in floats)
{
RefreshValue(pair.Key, pair.Value.ToString());
}
foreach (var pair in integers)
{
RefreshValue(pair.Key, pair.Value.ToString());
}
foreach (var pair in strings)
{
RefreshValue(pair.Key, pair.Value.ToString());
}
}
19
Source : StylishComponent.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public void Style(int damage)
{
if (damage != -1)
{
this.stylePoints += (float)((int)((float)(damage + 200) * this.chainRankMultiplier[this.chainKillRank]));
this.styleTotalDamage += damage;
this.chainKillRank = ((this.chainKillRank >= this.chainRankMultiplier.Length - 1) ? this.chainKillRank : (this.chainKillRank + 1));
this.chainTime = 5f;
this.styleHits++;
this.SetRank();
}
else if (this.stylePoints == 0f)
{
this.stylePoints += 1f;
this.SetRank();
}
this.startShake(5, 0.3f);
this.setPosition();
this.Labels["LabelTotal"].text = ((int)this.stylePoints).ToString();
this.Labels["LabelHits"].text = this.styleHits.ToString() + ((this.styleHits <= 1) ? "Hit" : "Hits");
if (this.chainKillRank == 0)
{
this.Labels["LabelChain"].text = string.Empty;
return;
}
this.Labels["LabelChain"].text = "x" + this.chainRankMultiplier[this.chainKillRank].ToString() + "!";
}
19
Source : RCActionHelper.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public string returnString(object sentObject)
{
object parameters = sentObject;
if (this.parameters != null)
{
parameters = this.parameters;
}
switch (this.helperClreplaced)
{
case 0:
return (string)parameters;
case 1:
{
RCActionHelper helper = (RCActionHelper)parameters;
switch (this.helperType)
{
case 0:
return this.nextHelper.returnString(RCManager.intVariables[helper.returnString(null)]);
case 1:
return this.nextHelper.returnString(RCManager.boolVariables[helper.returnString(null)]);
case 2:
return (string)RCManager.stringVariables[helper.returnString(null)];
case 3:
return this.nextHelper.returnString(RCManager.floatVariables[helper.returnString(null)]);
case 4:
return this.nextHelper.returnString(RCManager.playerVariables[helper.returnString(null)]);
case 5:
return this.nextHelper.returnString(RCManager.replacedanVariables[helper.returnString(null)]);
default:
return string.Empty;
}
}
case 2:
{
PhotonPlayer player = (PhotonPlayer)parameters;
if (player != null)
{
switch (this.helperType)
{
case 0:
return this.nextHelper.returnString(player.Properties["team"]);
case 1:
return this.nextHelper.returnString(player.Properties["RCteam"]);
case 2:
return this.nextHelper.returnString(player.Properties["dead"]);
case 3:
return this.nextHelper.returnString(player.Properties["isreplacedan"]);
case 4:
return this.nextHelper.returnString(player.Properties["kills"]);
case 5:
return this.nextHelper.returnString(player.Properties["deaths"]);
case 6:
return this.nextHelper.returnString(player.Properties["max_dmg"]);
case 7:
return this.nextHelper.returnString(player.Properties["total_dmg"]);
case 8:
return this.nextHelper.returnString(player.Properties["customInt"]);
case 9:
return this.nextHelper.returnString(player.Properties["customBool"]);
case 10:
return (string)player.Properties["customString"];
case 11:
return this.nextHelper.returnString(player.Properties["customFloat"]);
case 12:
return (string)player.Properties["name"];
case 13:
return (string)player.Properties["guildName"];
case 14:
{
int iD = player.ID;
if (RCManager.heroHash.ContainsKey(iD))
{
HERO hero = (HERO)RCManager.heroHash[iD];
return this.nextHelper.returnString(hero.transform.position.x);
}
return string.Empty;
}
case 15:
{
int key = player.ID;
if (RCManager.heroHash.ContainsKey(key))
{
HERO hero2 = (HERO)RCManager.heroHash[key];
return this.nextHelper.returnString(hero2.transform.position.y);
}
return string.Empty;
}
case 16:
{
int num6 = player.ID;
if (RCManager.heroHash.ContainsKey(num6))
{
HERO hero3 = (HERO)RCManager.heroHash[num6];
return this.nextHelper.returnString(hero3.transform.position.z);
}
return string.Empty;
}
case 17:
{
int num7 = player.ID;
if (RCManager.heroHash.ContainsKey(num7))
{
HERO hero4 = (HERO)RCManager.heroHash[num7];
return this.nextHelper.returnString(hero4.rigidbody.velocity.magnitude);
}
return string.Empty;
}
}
}
return string.Empty;
}
case 3:
{
replacedAN replacedan = (replacedAN)parameters;
if (replacedan != null)
{
switch (this.helperType)
{
case 0:
return this.nextHelper.returnString(replacedan.abnormalType);
case 1:
return this.nextHelper.returnString(replacedan.myLevel);
case 2:
return this.nextHelper.returnString(replacedan.currentHealth);
case 3:
return this.nextHelper.returnString(replacedan.transform.position.x);
case 4:
return this.nextHelper.returnString(replacedan.transform.position.y);
case 5:
return this.nextHelper.returnString(replacedan.transform.position.z);
}
}
return string.Empty;
}
case 4:
{
RCActionHelper helper2 = (RCActionHelper)parameters;
RCRegion region = (RCRegion)RCManager.RCRegions[helper2.returnString(null)];
switch (this.helperType)
{
case 0:
return this.nextHelper.returnString(region.GetRandomX());
case 1:
return this.nextHelper.returnString(region.GetRandomY());
case 2:
return this.nextHelper.returnString(region.GetRandomZ());
default:
return string.Empty;
}
}
case 5:
switch (this.helperType)
{
case 0:
return ((int)parameters).ToString();
case 1:
return ((bool)parameters).ToString();
case 2:
return (string)parameters;
case 3:
return ((float)parameters).ToString();
default:
return string.Empty;
}
default:
return string.Empty;
}
}
19
Source : ConversionTablePlugin.cs
with GNU General Public License v2.0
from afrantzis
with GNU General Public License v2.0
from afrantzis
void UpdateFloat(DataView dv)
{
long offset = dv.CursorOffset;
// make sure offset is valid for 32 bit float (and 64 bit)
if (offset < dv.Buffer.Size - 3 && offset >= 0) {
// create byte[] with float bytes
byte[] ba = new byte[8];
// fill byte[] according to endianess
if (littleEndian)
for (int i = 0; i < 4; i++)
ba[i] = dv.Buffer[offset+i];
else
for (int i = 0; i < 4; i++)
ba[3-i] = dv.Buffer[offset+i];
// set float 32bit
float f = BitConverter.ToSingle(ba, 0);
Float32bitEntry.Text = f.ToString();
// make sure offset is valid for 64 bit float
if (offset < dv.Buffer.Size - 7) {
// fill byte[] according to endianess
if (littleEndian)
for (int i = 4; i < 8; i++)
ba[i] = dv.Buffer[offset+i];
else
for (int i = 0; i < 8; i++)
ba[7-i] = dv.Buffer[offset+i];
// set float 64bit
double d = BitConverter.ToDouble(ba, 0);
Float64bitEntry.Text = d.ToString();
}
else
Float64bitEntry.Text = "---";
}
else {
ClearFloat();
}
}
19
Source : DefaultParamValueProcessors.cs
with MIT License
from aillieo
with MIT License
from aillieo
public string Save(float value)
{
return value.ToString();
}
19
Source : DependencyChecker.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
private static bool CheckForRageVersion(float MinimumVersion)
{
string RPHFile = "RAGEPluginHook.exe";
string[] files = Directory.GetFiles(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), "*.exe", SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
if (Path.GetFileName(file).ToLower() == "ragepluginhook.exe")
{
RPHFile = file;
break;
}
}
var versionInfo = FileVersionInfo.GetVersionInfo(RPHFile);
float Rageversion;
try
{
Rageversion = float.Parse(versionInfo.ProductVersion.Substring(0, 4), CultureInfo.InvariantCulture);
Game.LogTrivial("Albo1125.Common detected RAGEPluginHook version: " + Rageversion.ToString());
//If user's RPH version is older than the minimum
if (Rageversion < MinimumVersion)
{
CorrectRPHVersion = false;
}
//If user's RPH version is (above) the specified minimum
else
{
CorrectRPHVersion = true;
}
}
catch (Exception e)
{
//If for whatever reason the version couldn't be found.
Game.LogTrivial(e.ToString());
Game.LogTrivial("Unable to detect your Rage installation.");
if (File.Exists("RAGEPluginHook.exe"))
{
Game.LogTrivial("RAGEPluginHook.exe exists");
}
else { Game.LogTrivial("RAGEPluginHook doesn't exist."); }
Game.LogTrivial("Rage Version: " + versionInfo.ProductVersion.ToString());
Game.DisplayNotification("Albo1125.Common was unable to detect RPH installation. Please send me your logfile.");
CorrectRPHVersion = false;
}
return CorrectRPHVersion;
}
19
Source : actionChecker.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
[STAThread]
public void ProcessFile(string file, bool tryingAgain = false) {
//Custom 'file read delay'
float fileReadDelay = Properties.Settings.Default.FileReadDelay;
if (fileReadDelay > 0) {
MainProgram.DoDebug("User has set file delay to " + fileReadDelay.ToString() + "s, waiting before processing...");
Thread.Sleep((int)fileReadDelay * 1000);
}
if (!File.Exists(file)) {
MainProgram.DoDebug("File doesn't exist (anymore).");
return;
}
//Make sure the file isn't in use before trying to access it
int tries = 0;
while (FileInUse(file) || tries >= 20) {
tries++;
}
if (tries >= 20 && FileInUse(file)) {
MainProgram.DoDebug("File in use in use and can't be read. Try again.");
return;
}
//Check unique file ID (dublicate check)
ulong theFileUid = 0;
bool gotFileUid = false;
tries = 0;
while (!gotFileUid || tries >= 30) {
try {
theFileUid = getFileUID(file);
gotFileUid = true;
} catch {
Thread.Sleep(50);
}
}
if (tries >= 30 && !gotFileUid) {
MainProgram.DoDebug("File in use in use and can't be read. Try again.");
return;
}
//Validate UID
if (lastFileUid == 0) {
lastFileUid = Properties.Settings.Default.LastActionFileUid;
}
if (lastFileUid == theFileUid && !tryingAgain) {
//Often times this function is called three times per file - check if it has already been (or is being) processed
return;
}
if (executedFiles.Contains(theFileUid) && !tryingAgain) {
MainProgram.DoDebug("Tried to execute an already-executed file (UID " + theFileUid.ToString() + ")");
return;
}
lastFileUid = theFileUid;
executedFiles.Add(theFileUid);
Properties.Settings.Default.LastActionFileUid = lastFileUid;
Properties.Settings.Default.Save();
MainProgram.DoDebug("Processing file...");
string originalFileName = file, fullContent = "";
if (!File.Exists(file)) {
MainProgram.DoDebug("File no longer exists when trying to read file.");
return;
}
//READ FILE
if (new FileInfo(file).Length != 0) {
try {
string fileContent;
fileContent = File.ReadAllText(file);
fullContent = Regex.Replace(fileContent, @"\t|\r", "");
} catch (Exception e) {
if (unsuccessfulReads < 20) {
MainProgram.DoDebug("Failed to read file - trying again in 200ms... (trying max 20 times)");
unsuccessfulReads++;
Thread.Sleep(200);
ProcessFile(file, true);
return;
} else {
MainProgram.DoDebug("Could not read file on final try; " + e);
unsuccessfulReads = 0;
return;
}
}
MainProgram.DoDebug(" - Read complete, content: " + fullContent);
} else {
MainProgram.DoDebug(" - File is empty");
ErrorMessageBox("No action was set in the action file.");
}
//END READ
//DateTime lastModified = File.GetCreationTime(file);
DateTime lastModified = File.GetLastWriteTime(file);
if (lastModified.AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
//if (File.GetLastWriteTime(file).AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
//Extra security - sometimes the "creation" time is a bit behind, but the "modify" timestamp is usually right.
MainProgram.DoDebug("File creation time: " + lastModified.ToString());
MainProgram.DoDebug("Local time: " + DateTime.Now.ToString());
if (GettingStarted.isConfiguringActions) {
//Possibly configure an offset - if this always happens
Console.WriteLine("File is actually too old, but configuring the software to maybe set an offset");
isConfiguringOffset = true;
if (lastModifiedOffsets == null) {
lastModifiedOffsets = new List<double>();
}
lastModifiedOffsets.Add((DateTime.Now - lastModified).TotalSeconds);
if (lastModifiedOffsets.Count >= 3) {
int average = (int)(lastModifiedOffsets.Average());
Console.WriteLine("File Margin fixed offset set to; " + average.ToString());
Properties.Settings.Default.AutoFileMarginFixer = average;
Properties.Settings.Default.Save();
}
} else {
bool isGood = false;
if (Properties.Settings.Default.AutoFileMarginFixer != 0) {
//if (lastModified.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer) < DateTime.Now) {
var d1 = lastModified.AddSeconds(-Properties.Settings.Default.FileEditedMargin);
var d2 = DateTime.Now.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer);
if (d1 < d2) {
isGood = true;
MainProgram.DoDebug("File timestamp is actually more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, but the software is configured to have an auto-file-margin fix for " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s");
} else {
//MainProgram.DoDebug(d1.ToString());
//MainProgram.DoDebug(d2.ToString());
MainProgram.DoDebug("The " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s didn't fix it");
}
}
if (!isGood) {
MainProgram.DoDebug("The file is more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, meaning it won't be executed.");
new CleanupService().Start();
return;
}
}
//}
}
MainProgram.DoDebug("\n[ -- DOING ACTION(S) -- ]");
MainProgram.DoDebug(" - " + file + " UID; " + theFileUid);
MainProgram.DoDebug(" - File exists, checking the content...");
//Process the file
using (StringReader reader = new StringReader(fullContent)) {
string theLine = string.Empty;
do {
theLine = reader.ReadLine();
if (theLine != null) {
MainProgram.DoDebug("\n[EXECUTING ACTION]");
CheckAction(theLine, file);
}
} while (theLine != null);
}
MainProgram.DoDebug("[ -- DONE -- ]");
}
19
Source : Breathalyzer.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
internal static void TestNearestPedForAlcohol()
{
if (!Game.LocalPlayer.Character.IsInAnyVehicle(false) && !TrafficPolicerHandler.PerformingImpairmentTest)
{
TrafficPolicerHandler.PerformingImpairmentTest = true;
GameFiber.StartNew(delegate
{
Ped[] nearbypeds = Game.LocalPlayer.Character.GetNearbyPeds(1);
if (nearbypeds.Length != 0)
{
Ped nearestPed = nearbypeds[0];
if (nearestPed.Exists())
{
if (Vector3.Distance(nearestPed.Position, Game.LocalPlayer.Character.Position) < 2.5f && nearestPed.RelationshipGroup != "COP" && nearestPed.RelationshipGroup != "PLAYER" && nearestPed.IsHuman)
{
Game.LocalPlayer.Character.Inventory.GiveNewWeapon("WEAPON_UNARMED", 1, true);
AddPedToDictionaries(nearestPed);
AlcoholLevels PedAlcoholLevel = PedAlcoholLevels[nearestPed.Handle];
float Reading = DetermineAlcoholReading(nearestPed, PedAlcoholLevel);
try
{
if (!nearestPed.IsInAnyVehicle(false))
{
nearestPed.BlockPermanentEvents = true;
nearestPed.IsPersistent = true;
}
Rage.Native.NativeFunction.Natives.SET_PED_STEALTH_MOVEMENT(Game.LocalPlayer.Character, 0, 0);
Vector3 directionFromPedToNearest = (nearestPed.Position - Game.LocalPlayer.Character.Position);
directionFromPedToNearest.Normalize();
if (!nearestPed.IsInAnyVehicle(false))
{
nearestPed.Tasks.AchieveHeading(MathHelper.ConvertDirectionToHeading(directionFromPedToNearest) + 180f).WaitForCompletion(1500);
}
//Game.LocalPlayer.Character.Tasks.GoStraightToPosition(nearestPed.Position, MathHelper.ConvertDirectionToHeading(directionFromPedToNearest), 0.9f).WaitForCompletion(600);
directionFromPedToNearest = (nearestPed.Position - Game.LocalPlayer.Character.Position);
directionFromPedToNearest.Normalize();
Game.LocalPlayer.Character.Tasks.AchieveHeading(MathHelper.ConvertDirectionToHeading(directionFromPedToNearest)).WaitForCompletion(1600);
if (nearestPed.IsInAnyVehicle(false))
{
//Game.LocalPlayer.Character.Tasks.PlayAnimation("missfbi3_party_b", "walk_to_balcony_male2", 0.5f, AnimationFlags.None).WaitForCompletion(500);
Game.LocalPlayer.Character.Tasks.PlayAnimation("amb@code_human_police_investigate@idle_b", "idle_e", 2f, 0);
if(!nearestPed.CurrentVehicle.IsBike)
{
nearestPed.Tasks.PlayAnimation("amb@incar@male@smoking_low@idle_a", "idle_a", 2f, 0);
}
GameFiber.Sleep(2000);
}
else
{
nearestPed.Tasks.PlayAnimation("switch@michael@smoking", "michael_smoking_loop", 2f, AnimationFlags.SecondaryTask).WaitForCompletion(8000);
Game.LocalPlayer.Character.Tasks.Clear();
}
}
catch (Exception e) { }
finally
{
//GameFiber.Sleep(1800);
//Game.LocalPlayer.Character.Tasks.ClearImmediately();
uint noti = Game.DisplayNotification("Waiting for ~b~breathalyzer~s~ result...");
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "Breathalyzer tests conducted");
}
GameFiber.Sleep(3000);
Game.LocalPlayer.Character.Tasks.Clear();
Game.RemoveNotification(noti);
if (Reading == -1)
{
Game.DisplayNotification("The person ~r~failed to provide ~s~ a valid breath sample.");
}
else
{
Game.DisplayNotification("~b~Alcohol Reading: " + DetermineColourCode(PedAlcoholLevel) + Reading.ToString("n" + CountDigitsAfterDecimal(AlcoholLimit)) + AlcoholLimitUnit + ".~n~~b~Limit: " + AlcoholLimit.ToString() + "" + AlcoholLimitUnit + ".");
}
TrafficPolicerHandler.PerformingImpairmentTest = false;
if (nearestPed.Exists())
{
if (!nearestPed.IsInAnyVehicle(false))
{
if (nearestPed.LastVehicle.Exists())
{
if (nearestPed.DistanceTo(nearestPed.LastVehicle) < 20f)
{
if (IsPedOverTheLimit(nearestPed) && !TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Contains(nearestPed))
{
TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Add(nearestPed);
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "People caught driving over alcohol limit");
}
}
}
}
nearestPed.Tasks.StandStill(7000).WaitForCompletion(7000);
if (nearestPed.Exists())
{
if (!Functions.IsPedGettingArrested(nearestPed) && !Functions.IsPedArrested(nearestPed) && !Functions.IsPedStoppedByPlayer(nearestPed))
{
nearestPed.Dismiss();
}
}
}
else if (nearestPed.CurrentVehicle.Driver == nearestPed)
{
if (IsPedOverTheLimit(nearestPed) && !TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Contains(nearestPed))
{
TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Add(nearestPed);
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "People caught driving over alcohol limit");
}
}
}
}
}
}
}
}
TrafficPolicerHandler.PerformingImpairmentTest = false;
});
}
}
19
Source : Breathalyzer.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
private static int CountDigitsAfterDecimal(float value)
{
bool start = false;
int count = 0;
foreach (var s in value.ToString())
{
if (s == '.' || s == ',')
{
start = true;
}
else if (start)
{
count++;
}
}
//Game.LogTrivial("Decimal count: " + count.ToString());
return count + 1;
}
19
Source : SlugAgent.cs
with MIT License
from AleCamara
with MIT License
from AleCamara
public void FakeContinuosAgentStep(float[] action)
{
Debug.Log(string.Format("Agent Step (continuous): {0}, {1}", action[0].ToString(), action[1].ToString()));
float alpha_change = action[0];
alpha_change = Mathf.Clamp(alpha_change, -1f, 1f) * maxAlphaChangeDeg * Mathf.Deg2Rad;
float change_division = action[1];
change_division = Mathf.Clamp01(change_division);
DoUpdateSlugBody(alpha_change, change_division);
}
19
Source : SlugAgent.cs
with MIT License
from AleCamara
with MIT License
from AleCamara
public void DoUpdateSlugBody(float alphaChange, float t)
{
Debug.Log(string.Format("Update Slug Body: {0}, {1}", alphaChange.ToString(), t.ToString()));
float currentAlpha = Mathf.Clamp(_previousAlpha + alphaChange, 0f, Mathf.PI * 0.5f);
float delta_d = 2f * bodySeparation * (Mathf.Cos(currentAlpha) - Mathf.Cos(_previousAlpha));
float delta_xa = (t - 1f) * delta_d;
float delta_xb = t * delta_d;
bodyA.position += Vector3.right * delta_xa;
bodyB.position += Vector3.right * delta_xb;
Vector3 newPositionC = bodyC.position;
newPositionC.x = (bodyA.position.x + bodyB.position.x) * 0.5f;
newPositionC.y = bodyA.position.y + bodySeparation * Mathf.Sin(currentAlpha);
bodyC.position = newPositionC;
bodyPreA.position = bodyA.position - Vector3.right * bodySeparation;
bodyPreB.position = bodyB.position + Vector3.right * bodySeparation;
if (done == false)
{
float velocityC = (bodyC.position.x - _previousPositionC) / Time.fixedDeltaTime;
reward = 0f;
// Only apply bonus if displacement is positive (no increased penalty)
reward += velocityC * multiplierForBodyVelocity;
reward -= stepPenalty;
reward -= alphaChange * alphaChange * multiplierForActionSquared;
#if UNITY_EDITOR
Debug.Log("Reward: " + reward.ToString() + " ; replaced: " + replacedulativeReward.ToString());
#endif
}
_previousAlpha = currentAlpha;
_previousT = t;
}
19
Source : ProceduralWorldsGUI.cs
with MIT License
from alelievr
with MIT License
from alelievr
float Slider(GUIContent name, float value, ref float min, ref float max, float step = 0.01f, bool editableMin = true, bool editableMax = true, bool intMode = false, params PWGUIStyle[] styles)
{
int sliderLabelWidth = 30;
var e = Event.current;
foreach (var style in styles)
if (style.type == PWGUIStyleType.PrefixLabelWidth)
sliderLabelWidth = style.data;
if (name == null)
name = new GUIContent();
var fieldSettings = GetGUISettingData((intMode) ? PWGUIFieldType.IntSlider : PWGUIFieldType.Slider, () => {
return new PWGUISettings();
});
EditorGUILayout.BeginVertical();
{
EditorGUILayout.BeginHorizontal();
{
EditorGUI.BeginDisabledGroup(!editableMin);
min = EditorGUILayout.FloatField(min, GUILayout.Width(sliderLabelWidth));
EditorGUI.EndDisabledGroup();
if (step != 0)
{
float m = 1 / step;
value = Mathf.Round(GUILayout.HorizontalSlider(value, min, max) * m) / m;
}
else
value = GUILayout.HorizontalSlider(value, min, max);
EditorGUI.BeginDisabledGroup(!editableMax);
max = EditorGUILayout.FloatField(max, GUILayout.Width(sliderLabelWidth));
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(-4);
EditorGUILayout.BeginHorizontal();
{
if (!fieldSettings.editing)
{
name.text += value.ToString();
GUILayout.Label(name, Styles.centeredLabel);
Rect valueRect = GUILayoutUtility.GetLastRect();
if (valueRect.Contains(e.mousePosition) && e.type == EventType.MouseDown)
{
e.Use();
if (e.clickCount == 2)
fieldSettings.editing = true;
}
}
else
{
GUI.SetNextControlName("slider-value-" + value.GetHashCode());
GUILayout.FlexibleSpace();
value = EditorGUILayout.FloatField(value, GUILayout.Width(50));
Rect valueRect = GUILayoutUtility.GetLastRect();
GUILayout.FlexibleSpace();
if ((!valueRect.Contains(e.mousePosition) && e.type == EventType.MouseDown) || (e.isKey && e.keyCode == KeyCode.Return))
{ fieldSettings.editing = false; e.Use(); }
if (e.isKey && e.keyCode == KeyCode.Escape)
{ fieldSettings.editing = false; e.Use(); }
}
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
return value;
}
19
Source : BezierSpline.cs
with GNU General Public License v3.0
from AlexandreDoucet
with GNU General Public License v3.0
from AlexandreDoucet
public void AddDistanceMarker() {
while (this.transform.childCount != 0) {
DestroyImmediate (this.transform.GetChild (0).gameObject);
}
int numMarker = 10;
for (int i = 0; i < numMarker; i++) {
float distance = GetSplineLenght () / (float) (numMarker-1) * (float) i;
Vector3 position = GetPointFromParametricValue (distance);
GameObject marker = Instantiate (markerPrefab, position, Quaternion.idenreplacedy);
marker.transform.parent = this.transform;
marker.GetComponent<TextMesh> ().text = distance.ToString ();
}
}
19
Source : SplineToTerrainTools.cs
with GNU General Public License v3.0
from AlexandreDoucet
with GNU General Public License v3.0
from AlexandreDoucet
public void UpdateTrackMarker() {
Debug.Log ("Applying track markers");
float currentDistance = 0;
float splineLenght = spline.GetSplineLenght ();
while (this.transform.childCount != 0) {
DestroyImmediate (this.transform.GetChild (0).gameObject);
}
if (markerEnabled) {
while (currentDistance < splineLenght) {
Vector3 splinePoint = spline.GetPointFromParametricValue (currentDistance);
float yTerrainVal = tCE.WorldToTerrainHeight (new Vector2 (splinePoint.x, splinePoint.z));
TextMesh tM = Instantiate (textMesh, new Vector3 (splinePoint.x, yTerrainVal, splinePoint.z), Quaternion.idenreplacedy);
tM.transform.parent = this.transform;
tM.text = yTerrainVal.ToString ();
currentDistance = currentDistance + samplingStepSize;
}
}
}
19
Source : AxisLabels.cs
with GNU General Public License v3.0
from AlexandreDoucet
with GNU General Public License v3.0
from AlexandreDoucet
string UpdateLabels(DataGraph.Axis axis, List<RectTransform> textBoxes)
{
float unitAdjustement = 0;
if(!float.IsInfinity(axis.axisValueMinMax.y))
if (Mathf.Abs(axis.axisValueMinMax.y) > 10 || (Mathf.Abs(axis.axisValueMinMax.y) < 1))
{
while (Mathf.Abs(axis.axisValueMinMax.y) * Mathf.Pow(10f, -unitAdjustement) > 10)
{ unitAdjustement++; }
while (Mathf.Abs(axis.axisValueMinMax.y) * Mathf.Pow(10f, -unitAdjustement) < 1)
{ unitAdjustement--; }
}
for (int i = 0; i < dataPlot.horizontalAxis.majorMarkerList.Count; i++)
{
float width = Mathf.Abs(textBoxes[i].offsetMax.x - textBoxes[i].offsetMin.x);
float height = Mathf.Abs(textBoxes[i].offsetMax.y - textBoxes[i].offsetMin.y);
float posX = (axis.majorMarkerList[i].markerPosition) * (axis.stop.x - axis.start.x) + axis.start.x;
float posY = (axis.majorMarkerList[i].markerPosition) * (axis.stop.y - axis.start.y) + axis.start.y;
TextMeshProUGUI textMeshProUGUI = textBoxes[i].GetComponent<TextMeshProUGUI>();
if ((axis.stop.x - axis.start.x) > (axis.stop.y - axis.start.y))
{
textBoxes[i].ancreplaceddPosition = new Vector2(posX * parentWidth, posY * parentHeight-height) + horizontalOffset;
textMeshProUGUI.alignment = TextAlignmentOptions.Left;
}
else
{
textBoxes[i].ancreplaceddPosition = new Vector2(posX * parentWidth-width, posY * parentHeight - height/2f) + verticalOffset;
textMeshProUGUI.alignment = TextAlignmentOptions.Center;
}
double result = 0;
//if (unitAdjustement < -20)
//{
// result = 0;
//}
//else if (unitAdjustement > 20)
//{
// result = 0;
//}
//else
//{
result = Math.Round( Math.Pow(10f, -unitAdjustement)* ((double)(axis.majorMarkerList[i].markerPosition) * (double)(axis.axisValueMinMax.y - axis.axisValueMinMax.x) + (double)axis.axisValueMinMax.x) * 100.0) / 100.0;
//}
if (!double.IsNaN(result))
{
string str = String.Format("{0:F2}", result);
textMeshProUGUI.text = str;
}
else
{
textMeshProUGUI.text = "";
}
}
String unit = "10"+"<sup>"+ unitAdjustement.ToString() + "</sup>";
return unit;
}
19
Source : VelocityGetter.cs
with GNU General Public License v3.0
from AlexandreDoucet
with GNU General Public License v3.0
from AlexandreDoucet
void LateUpdate ()
{
lastVelocity = Mathf.Floor(playerRB.velocity.magnitude * 10000) / 10000;
vel.text = (lastVelocity).ToString();
graphSetter.AddToCurve(time, lastVelocity);
time += Time.deltaTime;
}
19
Source : MainForm.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void SendData(bool hardwareOnly)
{
computer.Accept(updateVisitor);
{
var gpuMaxTemp = Math.Max(
(int)MaxTemp(computer, HardwareType.GpuNvidia),
(int)MaxTemp(computer, HardwareType.GpuAti)
);
var gpuMaxUsage = Math.Max(
(int)UsageInPercent(computer, HardwareType.GpuAti, "GPU Core"),
(int)UsageInPercent(computer, HardwareType.GpuNvidia, "GPU Core")
);
var gpuMaxMemory = Math.Max(
(int)UsageInPercent(computer, HardwareType.GpuAti, "GPU Memory"),
(int)UsageInPercent(computer, HardwareType.GpuNvidia, "GPU Memory")
);
List<float> data = new List<float>
{
(int)MaxTemp(computer, HardwareType.CPU),
gpuMaxTemp,
(int)MaxTemp(computer, HardwareType.Mainboard),
(int)MaxTemp(computer, HardwareType.HDD),
(int)UsageInPercent(computer, HardwareType.CPU, "CPU Total"),
gpuMaxUsage,
(int)UsageInPercent(computer, HardwareType.RAM, "Memory"),
gpuMaxMemory
};
if (!hardwareOnly)
{
data.AddRange(new float[]{
// Right group.
settings.GetValue("nMaxFan", 100),
settings.GetValue("nMinFan", 20),
settings.GetValue("nMaxTemp", 100),
settings.GetValue("nMinTemp", 10),
// Flags
settings.GetValue("chkManualFan", false) ? 1 : 0,
settings.GetValue("chkManualColor", false) ? 1 : 0,
// Sliders.
settings.GetValue("sldManualFan", 50),
settings.GetValue("sldManualColor", 500),
settings.GetValue("sldLedBrightness", 50),
settings.GetValue("sldPlotInterval", 5),
settings.GetValue("cboMaxTempSource", 0),
});
};
string tmp = string.Join(";", data.Select(T => T.ToString()).ToArray());
serial.Write(Encoding.ASCII.GetBytes(tmp));
serial.Write(Encoding.ASCII.GetBytes("E"));
}
treeView.Invalidate();
plotPanel.InvalidatePlot();
systemTray.Redraw();
if (gadget != null)
{
gadget.Redraw();
}
if (wmiProvider != null)
{
wmiProvider.Update();
}
if (logSensors.Value && delayCount >= 4)
{
logger.Log();
}
if (delayCount < 4)
{
delayCount++;
}
}
19
Source : MainForm.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void timer_Tick(object sender, EventArgs e) {
computer.Accept(updateVisitor);
{
/*string tmp = "";
tmp += string.Format("{0};", (int)MaxTemp(computer, HardwareType.GpuAti) + AvgTemp(computer, HardwareType.GpuNvidia));
tmp += string.Format("{0};", (int)MaxTemp(computer, HardwareType.CPU));
tmp += string.Format("{0};", (int)MaxTemp(computer, HardwareType.Mainboard));
tmp += string.Format("{0};", (int)MaxTemp(computer, HardwareType.HDD));
tmp += string.Format("{0};", (int)(UsageInPercent(computer, HardwareType.GpuAti, "GPU Core") + UsageInPercent(computer, HardwareType.GpuNvidia, "GPU Core")));
tmp += string.Format("{0};", (int)UsageInPercent(computer, HardwareType.CPU, "CPU Total"));
tmp += string.Format("{0};", (int)UsageInPercent(computer, HardwareType.RAM, "Memory"));
tmp += string.Format("{0};", (int)UsageInPercent(computer, HardwareType.GpuAti, "GPU Memory") + UsageInPercent(computer, HardwareType.GpuNvidia, "GPU Memory"));*/
var gpuMaxTemp = Math.Max(
(int)MaxTemp(computer, HardwareType.GpuNvidia),
(int)MaxTemp(computer, HardwareType.GpuAti)
);
var gpuMaxUsage = Math.Max(
(int)UsageInPercent(computer, HardwareType.GpuAti, "GPU Core"),
(int)UsageInPercent(computer, HardwareType.GpuNvidia, "GPU Core")
);
var gpuMaxMemory = Math.Max(
(int)UsageInPercent(computer, HardwareType.GpuAti, "GPU Memory"),
(int)UsageInPercent(computer, HardwareType.GpuNvidia, "GPU Memory")
);
List <float> data = new List<float>
{
(int)MaxTemp(computer, HardwareType.CPU),
gpuMaxTemp,
(int)MaxTemp(computer, HardwareType.Mainboard),
(int)MaxTemp(computer, HardwareType.HDD),
(int)UsageInPercent(computer, HardwareType.CPU, "CPU Total"),
(int)gpuMaxUsage,
(int)UsageInPercent(computer, HardwareType.RAM, "Memory"),
(int)gpuMaxMemory,
// Right group.
settings.GetValue("nMaxFan", 100),
settings.GetValue("nMinFan", 20),
settings.GetValue("nMaxTemp", 100),
settings.GetValue("nMinTemp", 10),
// Flags
settings.GetValue("chkManualFan", false) ? 1 : 0,
settings.GetValue("chkManualColor", false) ? 1 : 0,
// Sliders.
settings.GetValue("sldManualFan", 50),
settings.GetValue("sldManualColor", 500),
settings.GetValue("sldLedBrightness", 50),
settings.GetValue("sldPlotInterval", 5),
settings.GetValue("cboMaxTempSource", 0),
};
string tmp = string.Join(";", data.Select(T => T.ToString()).ToArray());
serial.Write(Encoding.ASCII.GetBytes(tmp));
serial.Write(Encoding.ASCII.GetBytes("E"));
/*var gpus = computer.Hardware.Where(x => x.HardwareType == HardwareType.GpuAti || x.HardwareType == HardwareType.GpuNvidia).ToArray();
if (gpus.Any())
{
var gpu = gpus.First();
var temps = gpu.Sensors.Where(x => x.SensorType == SensorType.Temperature).ToArray();
if (temps.Any())
{
var temp = temps.Average(x => x.Value.Value);
tmp += string.Format("gpu: {0}C\r", (int)temp);
}
}
var cpus = computer.Hardware.Where(x => x.HardwareType == HardwareType.CPU).ToArray();
if (cpus.Any())
{
var cpu = cpus.First();
var temps = cpu.Sensors.Where(x => x.SensorType == SensorType.Temperature).ToArray();
if (temps.Any())
{
var temp = temps.Average(x => x.Value.Value);
tmp += string.Format("cpu: {0}C\r", (int)temp);
}
}
var mainboard = computer.Hardware.Where(x => x.HardwareType == HardwareType.Mainboard).Single();
{
var temps = mainboard.Sensors.Where(x => x.SensorType == SensorType.Temperature).ToArray();
if (temps.Any())
{
var temp = temps.Average(x => x.Value.Value);
tmp += string.Format("mainboard: {0}C\r", (int)temp);
}
}
var hdds = computer.Hardware.Where(x => x.HardwareType == HardwareType.CPU).ToArray();
if (hdds.Any())
{
var cpu = cpus.First();
var temps = cpu.Sensors.Where(x => x.SensorType == SensorType.Temperature).ToArray();
if (temps.Any())
{
var temp = temps.Average(x => x.Value.Value);
tmp += string.Format("hdd: {0}C\r", (int)temp);
}
}*/
}
treeView.Invalidate();
plotPanel.InvalidatePlot();
systemTray.Redraw();
if (gadget != null) {
gadget.Redraw();
}
if (wmiProvider != null) {
wmiProvider.Update();
}
if (logSensors.Value && delayCount >= 4) {
logger.Log();
}
if (delayCount < 4) {
delayCount++;
}
}
19
Source : RangedFloatNode.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
void DrawFakeFloatMaterial( DrawInfo drawInfo )
{
if( m_floatMode )
{
//UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_materialValue, LabelWidth * drawInfo.InvertedZoom );
Rect fakeField = m_propertyDrawPos;
fakeField.xMin += LabelWidth * drawInfo.InvertedZoom;
if( GUI.enabled )
{
Rect fakeLabel = m_propertyDrawPos;
fakeLabel.xMax = fakeField.xMin;
EditorGUIUtility.AddCursorRect( fakeLabel, MouseCursor.SlideArrow );
EditorGUIUtility.AddCursorRect( fakeField, MouseCursor.Text );
}
if( m_previousValue[ 0 ] != m_materialValue )
{
m_previousValue[ 0 ] = m_materialValue;
m_fieldText[ 0 ] = m_materialValue.ToString();
}
GUI.Label( fakeField, m_fieldText[ 0 ], UIUtils.MainSkin.textField );
}
else
{
DrawFakeSlider( ref m_materialValue, drawInfo );
}
}
19
Source : ParallaxOcclusionMappingNode.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( !m_texPort.IsConnected )
{
UIUtils.ShowMessage( "Parallax Occlusion Mapping node only works if a Texture Object is connected to its Tex (R) port" );
return "0";
}
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
WirePortDataType texType = ( m_pomTexType == POMTexTypes.Texture3D )?WirePortDataType.SAMPLER3D: WirePortDataType.SAMPLER2D;
GeneratePOMfunction();
string arrayIndex = m_arrayIndexPort.Visible?m_arrayIndexPort.GeneratePortInstructions( ref dataCollector ):"0";
string textcoords = m_uvPort.GeneratePortInstructions( ref dataCollector );
if( m_pomTexType == POMTexTypes.Texture3D )
{
string texName = "pomTexCoord" + OutputId;
dataCollector.AddToLocalVariables( UniqueId, m_currentPrecisionType, WirePortDataType.FLOAT3, texName, string.Format( "float3({0},{1})", textcoords, arrayIndex ) );
textcoords = texName;
}
string texture = m_texPort.GenerateShaderForOutput( ref dataCollector, texType,false,true );
string scale = m_defaultScale.ToString();
if( m_scalePort.IsConnected )
scale = m_scalePort.GeneratePortInstructions( ref dataCollector );
string viewDirTan = "";
if ( !m_viewdirTanPort.IsConnected )
{
if ( !dataCollector.DirtyNormal )
dataCollector.ForceNormal = true;
if ( dataCollector.IsTemplate )
{
viewDirTan = dataCollector.TemplateDataCollectorInstance.GetTangentViewDir( m_currentPrecisionType );
}
else
{
viewDirTan = GeneratorUtils.GenerateViewDirection( ref dataCollector, UniqueId, ViewSpace.Tangent );
//dataCollector.AddToInput( UniqueId, SurfaceInputs.VIEW_DIR, m_currentPrecisionType );
//viewDirTan = Constants.InputVarStr + "." + UIUtils.GetInputValueFromType( SurfaceInputs.VIEW_DIR );
}
}
else
{
viewDirTan = m_viewdirTanPort.GeneratePortInstructions( ref dataCollector );
}
//generate world normal
string normalWorld = string.Empty;
if ( dataCollector.IsTemplate )
{
normalWorld = dataCollector.TemplateDataCollectorInstance.GetWorldNormal( m_currentPrecisionType );
}
else
{
dataCollector.AddToInput( UniqueId, SurfaceInputs.WORLD_NORMAL, m_currentPrecisionType );
dataCollector.AddToInput( UniqueId, SurfaceInputs.INTERNALDATA, addSemiColon: false );
normalWorld = GeneratorUtils.GenerateWorldNormal( ref dataCollector, UniqueId );
}
//string normalWorld = "WorldNormalVector( " + Constants.InputVarStr + ", float3( 0, 0, 1 ) )";
//generate viewDir in world space
//string worldPos = string.Empty;
//if( dataCollector.IsTemplate )
//{
// worldPos = dataCollector.TemplateDataCollectorInstance.GetWorldPos();
//}
//else
//{
// dataCollector.AddToInput( UniqueId, SurfaceInputs.WORLD_POS );
// worldPos = Constants.InputVarStr + ".worldPos";
//}
//if( !dataCollector.IsTemplate )
// dataCollector.AddToInput( UniqueId, SurfaceInputs.WORLD_POS );
string worldViewDir = GeneratorUtils.GenerateViewDirection( ref dataCollector, UniqueId, ViewSpace.World );
//dataCollector.AddToLocalVariables( UniqueId, m_currentPrecisionType, WirePortDataType.FLOAT3, WorldDirVarStr, TemplateHelperFunctions.WorldSpaceViewDir( dataCollector, worldPos, true ) );
string dx = "ddx("+ textcoords + ")";
string dy = "ddy(" + textcoords + ")";
string refPlane = m_defaultRefPlane.ToString();
if ( m_refPlanePort.IsConnected )
refPlane = m_refPlanePort.GeneratePortInstructions( ref dataCollector );
string curvature = "float2("+ m_CurvatureVector.x + "," + m_CurvatureVector.y + ")";
if ( m_useCurvature )
{
dataCollector.AddToProperties( UniqueId, "[Header(Parallax Occlusion Mapping)]", 300 );
dataCollector.AddToProperties( UniqueId, "_CurvFix(\"Curvature Bias\", Range( 0 , 1)) = 1", 301 );
dataCollector.AddToUniforms( UniqueId, "uniform float _CurvFix;" );
if ( m_curvaturePort.IsConnected )
curvature = m_curvaturePort.GeneratePortInstructions( ref dataCollector );
}
string localVarName = "OffsetPOM" + UniqueId;
string textureSTType = dataCollector.IsSRP ? "float4 " : "uniform float4 ";
dataCollector.AddToUniforms(UniqueId, textureSTType + texture +"_ST;");
if( m_pomTexType == POMTexTypes.TextureArray )
dataCollector.UsingArrayDerivatives = true;
string textureArgs = string.Empty;
if( m_pomTexType == POMTexTypes.TextureArray )
{
if( UIUtils.CurrentWindow.OutsideGraph.IsSRP )
{
textureArgs = "TEXTURE2D_ARRAY_PARAM(" + texture +" , "+"sampler##"+texture + ")";
}
else
{
textureArgs = "UNITY_Preplaced_TEX2DARRAY(" + texture + ")";
}
}
else
{
textureArgs = texture;
}
//string functionResult = dataCollector.AddFunctions( m_functionHeader, m_functionBody, ( (m_pomTexType == POMTexTypes.TextureArray) ? "UNITY_Preplaced_TEX2DARRAY(" + texture + ")": texture), textcoords, dx, dy, normalWorld, worldViewDir, viewDirTan, m_minSamples, m_maxSamples, scale, refPlane, texture+"_ST.xy", curvature, arrayIndex );
string functionResult = dataCollector.AddFunctions( m_functionHeader, m_functionBody, textureArgs, textcoords, dx, dy, normalWorld, worldViewDir, viewDirTan, m_inlineMinSamples.GetValueOrProperty(false), m_inlineMinSamples.GetValueOrProperty(false), scale, refPlane, texture + "_ST.xy", curvature, arrayIndex );
dataCollector.AddToLocalVariables( UniqueId, m_currentPrecisionType, m_pomUVPort.DataType, localVarName, functionResult );
return GetOutputVectorItem( 0, outputId, localVarName );
}
19
Source : RangedFloatNode.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( !m_isVisible )
return;
if ( m_isEditingFields && m_currentParameterType != PropertyType.Global )
{
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
{
EditorGUI.BeginChangeCheck();
if ( m_floatMode )
{
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_materialValue, LabelWidth * drawInfo.InvertedZoom );
}
else
{
DrawSlider( ref m_materialValue, drawInfo );
}
if ( EditorGUI.EndChangeCheck() )
{
m_requireMaterialUpdate = true;
if ( m_currentParameterType != PropertyType.Constant )
{
BeginDelayedDirtyProperty();
}
}
}
else
{
EditorGUI.BeginChangeCheck();
if ( m_floatMode )
{
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_defaultValue, LabelWidth * drawInfo.InvertedZoom );
}
else
{
DrawSlider( ref m_defaultValue, drawInfo );
}
if ( EditorGUI.EndChangeCheck() )
{
BeginDelayedDirtyProperty();
}
}
}
else if ( drawInfo.CurrentEventType == EventType.Repaint && ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD4 )
{
if( m_currentParameterType == PropertyType.Global )
{
bool guiEnabled = GUI.enabled;
GUI.enabled = false;
DrawFakeFloatMaterial( drawInfo );
GUI.enabled = guiEnabled;
}
else if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
{
DrawFakeFloatMaterial( drawInfo );
}
else
{
if ( m_floatMode )
{
//UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_defaultValue, LabelWidth * drawInfo.InvertedZoom );
Rect fakeField = m_propertyDrawPos;
fakeField.xMin += LabelWidth * drawInfo.InvertedZoom;
Rect fakeLabel = m_propertyDrawPos;
fakeLabel.xMax = fakeField.xMin;
EditorGUIUtility.AddCursorRect( fakeLabel, MouseCursor.SlideArrow );
EditorGUIUtility.AddCursorRect( fakeField, MouseCursor.Text );
if ( m_previousValue[ 0 ] != m_defaultValue )
{
m_previousValue[ 0 ] = m_defaultValue;
m_fieldText[ 0 ] = m_defaultValue.ToString();
}
GUI.Label( fakeField, m_fieldText[ 0 ], UIUtils.MainSkin.textField );
}
else
{
DrawFakeSlider( ref m_defaultValue, drawInfo );
}
}
}
}
19
Source : RangedFloatNode.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
void DrawFakeSlider( ref float value, DrawInfo drawInfo )
{
float rangeWidth = 30 * drawInfo.InvertedZoom;
float rangeSpacing = 5 * drawInfo.InvertedZoom;
//Min
Rect minRect = m_propertyDrawPos;
minRect.width = rangeWidth;
EditorGUIUtility.AddCursorRect( minRect, MouseCursor.Text );
if ( m_previousValue[ 1 ] != m_min )
{
m_previousValue[ 1 ] = m_min;
m_fieldText[ 1 ] = m_min.ToString();
}
GUI.Label( minRect, m_fieldText[ 1 ], UIUtils.MainSkin.textField );
//Value Area
Rect valRect = m_propertyDrawPos;
valRect.width = rangeWidth;
valRect.x = m_propertyDrawPos.xMax - rangeWidth - rangeWidth - rangeSpacing;
EditorGUIUtility.AddCursorRect( valRect, MouseCursor.Text );
if ( m_previousValue[ 0 ] != value )
{
m_previousValue[ 0 ] = value;
m_fieldText[ 0 ] = value.ToString();
}
GUI.Label( valRect, m_fieldText[ 0 ], UIUtils.MainSkin.textField );
//Max
Rect maxRect = m_propertyDrawPos;
maxRect.width = rangeWidth;
maxRect.x = m_propertyDrawPos.xMax - rangeWidth;
EditorGUIUtility.AddCursorRect( maxRect, MouseCursor.Text );
if ( m_previousValue[ 2 ] != m_max )
{
m_previousValue[ 2 ] = m_max;
m_fieldText[ 2 ] = m_max.ToString();
}
GUI.Label( maxRect, m_fieldText[ 2 ], UIUtils.MainSkin.textField );
Rect sliderValRect = m_propertyDrawPos;
sliderValRect.x = minRect.xMax + rangeSpacing;
sliderValRect.xMax = valRect.xMin - rangeSpacing;
Rect sliderBackRect = sliderValRect;
sliderBackRect.height = 5 * drawInfo.InvertedZoom;
sliderBackRect.center = new Vector2( sliderValRect.center.x, Mathf.Round( sliderValRect.center.y ) );
GUI.Label( sliderBackRect, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SliderStyle ) );
sliderValRect.width = 10;
float percent = ( value - m_min) / ( m_max-m_min );
sliderValRect.x += percent * (sliderBackRect.width - 10 * drawInfo.InvertedZoom );
GUI.Label( sliderValRect, string.Empty, UIUtils.RangedFloatSliderThumbStyle );
}
19
Source : FallbackFloat.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public override string ToString()
{
return m_current.ToString();
}
19
Source : AppendNode.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar )
{
if ( m_outputPorts[ 0 ].IsLocalValue( dataCollector.PortCategory ) )
return m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory );
string value = string.Empty;
switch ( m_selectedOutputType )
{
case WirePortDataType.FLOAT4:
case WirePortDataType.OBJECT:
case WirePortDataType.COLOR:
{
value = "float4( ";
for ( int i = 0; i < 4; i++ )
{
value += m_inputPorts[ i ].IsConnected ? InputPorts[ i ].GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT, ignoreLocalVar, true ) : m_defaultValues[ i ].ToString();
if ( i != 3 )
value += " , ";
}
value += " )";
}
break;
case WirePortDataType.FLOAT3:
{
value = "float3( ";
for ( int i = 0; i < 3; i++ )
{
value += m_inputPorts[ i ].IsConnected ? InputPorts[ i ].GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT, ignoreLocalVar, true ) : m_defaultValues[ i ].ToString();
if ( i != 2 )
value += " , ";
}
value += " )";
}
break;
case WirePortDataType.FLOAT2:
{
value = "float2( ";
for ( int i = 0; i < 2; i++ )
{
value += m_inputPorts[ i ].IsConnected ? InputPorts[ i ].GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT, ignoreLocalVar, true ) : m_defaultValues[ i ].ToString();
if ( i != 1 )
value += " , ";
}
value += " )";
}
break;
case WirePortDataType.FLOAT:
case WirePortDataType.INT:
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{ }
break;
}
RegisterLocalVariable( 0, value, ref dataCollector, "appendResult" + OutputId );
return m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory );
}
19
Source : ScaleNode.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( !m_isVisible )
return;
if ( m_isEditingFields )
{
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_scaleFactor, LabelWidth );
}
else if ( drawInfo.CurrentEventType == EventType.Repaint )
{
Rect fakeField = m_propertyDrawPos;
fakeField.xMin += LabelWidth * drawInfo.InvertedZoom;
Rect fakeLabel = m_propertyDrawPos;
fakeLabel.xMax = fakeField.xMin;
EditorGUIUtility.AddCursorRect( fakeLabel, MouseCursor.SlideArrow );
EditorGUIUtility.AddCursorRect( fakeField, MouseCursor.Text );
if ( m_previousValue != m_scaleFactor )
{
m_previousValue = m_scaleFactor;
m_fieldText = m_scaleFactor.ToString();
}
GUI.Label( fakeField, m_fieldText, UIUtils.MainSkin.textField );
}
}
19
Source : CustomMaterialInspector.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public override void OnGUI( MaterialEditor materialEditor, MaterialProperty[] properties )
{
IOUtils.Init();
Material mat = materialEditor.target as Material;
if( mat == null )
return;
m_instance = materialEditor;
if( !m_initialized )
{
Init();
m_initialized = true;
Undo.undoRedoPerformed += UndoRedoPerformed;
}
if( Event.current.type == EventType.Repaint &&
mat.HasProperty( IOUtils.DefaultASEDirtyCheckId ) &&
mat.GetInt( IOUtils.DefaultASEDirtyCheckId ) == 1 )
{
mat.SetInt( IOUtils.DefaultASEDirtyCheckId, 0 );
UIUtils.ForceUpdateFromMaterial();
//Event.current.Use();
}
if( materialEditor.isVisible )
{
GUILayout.BeginVertical();
{
GUILayout.Space( 3 );
if( GUILayout.Button( "Open in Shader Editor" ) )
{
#if UNITY_2018_3_OR_NEWER
ASEPackageManagerHelper.SetupLateMaterial( mat );
#else
AmplifyShaderEditorWindow.LoadMaterialToASE( mat );
#endif
}
GUILayout.BeginHorizontal();
{
if( GUILayout.Button( CopyButtonStr ) )
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Shader shader = mat.shader;
int propertyCount = UnityEditor.ShaderUtil.GetPropertyCount( shader );
string allProperties = string.Empty;
for( int i = 0; i < propertyCount; i++ )
{
UnityEditor.ShaderUtil.ShaderPropertyType type = UnityEditor.ShaderUtil.GetPropertyType( shader, i );
string name = UnityEditor.ShaderUtil.GetPropertyName( shader, i );
string valueStr = string.Empty;
switch( type )
{
case UnityEditor.ShaderUtil.ShaderPropertyType.Color:
{
Color value = mat.GetColor( name );
valueStr = value.r.ToString() + IOUtils.VECTOR_SEPARATOR +
value.g.ToString() + IOUtils.VECTOR_SEPARATOR +
value.b.ToString() + IOUtils.VECTOR_SEPARATOR +
value.a.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Vector:
{
Vector4 value = mat.GetVector( name );
valueStr = value.x.ToString() + IOUtils.VECTOR_SEPARATOR +
value.y.ToString() + IOUtils.VECTOR_SEPARATOR +
value.z.ToString() + IOUtils.VECTOR_SEPARATOR +
value.w.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Float:
{
float value = mat.GetFloat( name );
valueStr = value.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Range:
{
float value = mat.GetFloat( name );
valueStr = value.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv:
{
Texture value = mat.GetTexture( name );
valueStr = replacedetDatabase.GetreplacedetPath( value );
Vector2 offset = mat.GetTextureOffset( name );
Vector2 scale = mat.GetTextureScale( name );
valueStr += IOUtils.VECTOR_SEPARATOR + scale.x.ToString() +
IOUtils.VECTOR_SEPARATOR + scale.y.ToString() +
IOUtils.VECTOR_SEPARATOR + offset.x.ToString() +
IOUtils.VECTOR_SEPARATOR + offset.y.ToString();
}
break;
}
allProperties += name + IOUtils.FIELD_SEPARATOR + type + IOUtils.FIELD_SEPARATOR + valueStr;
if( i < ( propertyCount - 1 ) )
{
allProperties += IOUtils.LINE_TERMINATOR;
}
}
EditorPrefs.SetString( IOUtils.MAT_CLIPBOARD_ID, allProperties );
System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
}
if( GUILayout.Button( PasteButtonStr ) )
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
string propertiesStr = EditorPrefs.GetString( IOUtils.MAT_CLIPBOARD_ID, string.Empty );
if( !string.IsNullOrEmpty( propertiesStr ) )
{
string[] propertyArr = propertiesStr.Split( IOUtils.LINE_TERMINATOR );
bool validData = true;
try
{
for( int i = 0; i < propertyArr.Length; i++ )
{
string[] valuesArr = propertyArr[ i ].Split( IOUtils.FIELD_SEPARATOR );
if( valuesArr.Length != 3 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else if( mat.HasProperty( valuesArr[ 0 ] ) )
{
UnityEditor.ShaderUtil.ShaderPropertyType type = (UnityEditor.ShaderUtil.ShaderPropertyType)Enum.Parse( typeof( UnityEditor.ShaderUtil.ShaderPropertyType ), valuesArr[ 1 ] );
switch( type )
{
case UnityEditor.ShaderUtil.ShaderPropertyType.Color:
{
string[] colorVals = valuesArr[ 2 ].Split( IOUtils.VECTOR_SEPARATOR );
if( colorVals.Length != 4 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else
{
mat.SetColor( valuesArr[ 0 ], new Color( Convert.ToSingle( colorVals[ 0 ] ),
Convert.ToSingle( colorVals[ 1 ] ),
Convert.ToSingle( colorVals[ 2 ] ),
Convert.ToSingle( colorVals[ 3 ] ) ) );
}
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Vector:
{
string[] vectorVals = valuesArr[ 2 ].Split( IOUtils.VECTOR_SEPARATOR );
if( vectorVals.Length != 4 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else
{
mat.SetVector( valuesArr[ 0 ], new Vector4( Convert.ToSingle( vectorVals[ 0 ] ),
Convert.ToSingle( vectorVals[ 1 ] ),
Convert.ToSingle( vectorVals[ 2 ] ),
Convert.ToSingle( vectorVals[ 3 ] ) ) );
}
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Float:
{
mat.SetFloat( valuesArr[ 0 ], Convert.ToSingle( valuesArr[ 2 ] ) );
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Range:
{
mat.SetFloat( valuesArr[ 0 ], Convert.ToSingle( valuesArr[ 2 ] ) );
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv:
{
string[] texVals = valuesArr[ 2 ].Split( IOUtils.VECTOR_SEPARATOR );
if( texVals.Length != 5 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else
{
mat.SetTexture( valuesArr[ 0 ], replacedetDatabase.LoadreplacedetAtPath<Texture>( texVals[ 0 ] ) );
mat.SetTextureScale( valuesArr[ 0 ], new Vector2( Convert.ToSingle( texVals[ 1 ] ), Convert.ToSingle( texVals[ 2 ] ) ) );
mat.SetTextureOffset( valuesArr[ 0 ], new Vector2( Convert.ToSingle( texVals[ 3 ] ), Convert.ToSingle( texVals[ 4 ] ) ) );
}
}
break;
}
}
}
}
catch( Exception e )
{
Debug.LogException( e );
validData = false;
}
if( validData )
{
materialEditor.PropertiesChanged();
UIUtils.CopyValuesFromMaterial( mat );
}
else
{
EditorPrefs.SetString( IOUtils.MAT_CLIPBOARD_ID, string.Empty );
}
}
System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
}
}
GUILayout.EndHorizontal();
GUILayout.Space( 5 );
}
GUILayout.EndVertical();
}
EditorGUI.BeginChangeCheck();
//base.OnGUI( materialEditor, properties );
// Draw custom properties instead of calling BASE to use single line texture properties
materialEditor.SetDefaultGUIWidths();
if( m_infoField == null )
{
m_infoField = typeof( MaterialEditor ).GetField( "m_InfoMessage", BindingFlags.Instance | BindingFlags.NonPublic );
}
string info = m_infoField.GetValue( materialEditor ) as string;
if( !string.IsNullOrEmpty( info ) )
{
EditorGUILayout.HelpBox( info, MessageType.Info );
}
else
{
GUIUtility.GetControlID( "EditorTextField".GetHashCode(), FocusType.Preplacedive, new Rect( 0f, 0f, 0f, 0f ) );
}
for( int i = 0; i < properties.Length; i++ )
{
if( ( properties[ i ].flags & ( MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData ) ) == MaterialProperty.PropFlags.None )
{
if( ( properties[ i ].flags & MaterialProperty.PropFlags.NoScaleOffset ) == MaterialProperty.PropFlags.NoScaleOffset )
{
object obj = MaterialPropertyHandlerEx.GetHandler( mat.shader, properties[ i ].name );
if( obj != null )
{
float height = MaterialPropertyHandlerEx.GetPropertyHeight( obj, properties[ i ], properties[ i ].displayName, materialEditor );
//Rect rect = (Rect)materialEditor.GetType().InvokeMember( "GetPropertyRect", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, materialEditor, new object[] { properties[ i ], properties[ i ].displayName, true } );
Rect rect = EditorGUILayout.GetControlRect( true, height, EditorStyles.layerMaskField );
MaterialPropertyHandlerEx.OnGUI( obj, ref rect, properties[ i ], new GUIContent( properties[ i ].displayName ), materialEditor );
if( MaterialPropertyHandlerEx.PropertyDrawer( obj ) != null )
continue;
rect = EditorGUILayout.GetControlRect( true, height, EditorStyles.layerMaskField );
materialEditor.TexturePropertyMiniThumbnail( rect, properties[ i ], properties[ i ].displayName, string.Empty );
}
else
{
materialEditor.TexturePropertySingleLine( new GUIContent( properties[ i ].displayName ), properties[ i ] );
}
}
else
{
float propertyHeight = materialEditor.GetPropertyHeight( properties[ i ], properties[ i ].displayName );
Rect controlRect = EditorGUILayout.GetControlRect( true, propertyHeight, EditorStyles.layerMaskField, new GUILayoutOption[ 0 ] );
materialEditor.ShaderProperty( controlRect, properties[ i ], properties[ i ].displayName );
}
}
}
EditorGUILayout.Space();
materialEditor.RenderQueueField();
#if UNITY_5_6_OR_NEWER
materialEditor.EnableInstancingField();
#endif
#if UNITY_5_6_2 || UNITY_5_6_3 || UNITY_5_6_4 || UNITY_2017_1_OR_NEWER
materialEditor.DoubleSidedGIField();
#endif
materialEditor.LightmapEmissionProperty();
if( m_refreshOnUndo || EditorGUI.EndChangeCheck() )
{
m_refreshOnUndo = false;
string isEmissive = mat.GetTag( "IsEmissive", false, "false" );
if( isEmissive.Equals( "true" ) )
{
mat.globalIlluminationFlags &= (MaterialGlobalIlluminationFlags)3;
}
else
{
mat.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
UIUtils.CopyValuesFromMaterial( mat );
}
if( materialEditor.RequiresConstantRepaint() && m_lastRenderedTime + 0.032999999821186066 < EditorApplication.timeSinceStartup )
{
this.m_lastRenderedTime = EditorApplication.timeSinceStartup;
materialEditor.Repaint();
}
}
19
Source : InputPort.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
void UpdateInternalDataFromVariables( bool forceDecimal = false )
{
switch( m_dataType )
{
case WirePortDataType.OBJECT:
case WirePortDataType.FLOAT:
{
if( forceDecimal && m_previewInternalFloat == (int)m_previewInternalFloat )
m_internalData = m_previewInternalFloat.ToString("0.0##############"); // to make sure integer values like 0 or 1 are generated as 0.0 and 1.0
else
m_internalData = m_previewInternalFloat.ToString();
m_internalDataWrapper = string.Empty;
}
break;
case WirePortDataType.INT:
{
m_internalData = m_previewInternalInt.ToString();
m_internalDataWrapper = string.Empty;
}
break;
case WirePortDataType.FLOAT2:
{
m_internalData = m_previewInternalVec2.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec2.y.ToString();
m_internalDataWrapper = "float2( {0} )";
}
break;
case WirePortDataType.FLOAT3:
{
m_internalData = m_previewInternalVec3.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec3.y.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec3.z.ToString();
m_internalDataWrapper = "float3( {0} )";
}
break;
case WirePortDataType.FLOAT4:
{
m_internalData = m_previewInternalVec4.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec4.y.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec4.z.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec4.w.ToString();
m_internalDataWrapper = "float4( {0} )";
}
break;
case WirePortDataType.COLOR:
{
m_internalData = m_previewInternalColor.r.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalColor.g.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalColor.b.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalColor.a.ToString();
m_internalDataWrapper = "float4( {0} )";
}
break;
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{
m_internalData = m_previewInternalMatrix4x4[ 0, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 0, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 0, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 0, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalMatrix4x4[ 1, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 1, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 1, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 1, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalMatrix4x4[ 2, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 2, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 2, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 2, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalMatrix4x4[ 3, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 3, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 3, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 3, 3 ].ToString();
if( m_dataType == WirePortDataType.FLOAT3x3 )
m_internalDataWrapper = "float3x3( {0} )";
else
m_internalDataWrapper = "float4x4( {0} )";
}
break;
}
}
19
Source : InlineProperty.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public string GetValueOrProperty( bool parentesis = true )
{
if( m_active )
{
PropertyNode node = GetPropertyNode();
if( node != null )
{
return parentesis ? "[" + node.PropertyName + "]" : node.PropertyName;
}
else
{
m_active = false;
m_nodeId = -1;
return m_value.ToString();
}
}
else
{
return m_value.ToString();
}
}
19
Source : InlineProperty.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public string GetValueOrProperty( string defaultValue, bool parentesis = true )
{
if( m_active )
{
PropertyNode node = GetPropertyNode();
if( node != null )
{
return parentesis ? "[" + node.PropertyName + "]" : node.PropertyName;
}
else if( !string.IsNullOrEmpty( defaultValue ) )
{
m_active = false;
m_nodeId = -1;
return defaultValue;
}
else
{
m_active = false;
m_nodeId = -1;
return m_value.ToString();
}
}
else
{
return defaultValue;
}
}
19
Source : IOUtils.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public static string Floatify( float value )
{
return ( value % 1 ) != 0 ? value.ToString() : ( value.ToString() + FloatifyStr );
}
19
Source : ParallaxOcclusionMappingNode.cs
with GNU General Public License v3.0
from alexismorin
with GNU General Public License v3.0
from alexismorin
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
WirePortDataType texType = ( m_pomTexType == POMTexTypes.Texture3D )?WirePortDataType.SAMPLER3D: WirePortDataType.SAMPLER2D;
GeneratePOMfunction();
string arrayIndex = m_arrayIndexPort.Visible?m_arrayIndexPort.GeneratePortInstructions( ref dataCollector ):"0";
string textcoords = m_uvPort.GeneratePortInstructions( ref dataCollector );
if( m_pomTexType == POMTexTypes.Texture3D )
{
string texName = "pomTexCoord" + OutputId;
dataCollector.AddToLocalVariables( UniqueId, m_currentPrecisionType, WirePortDataType.FLOAT3, texName, string.Format( "float3({0},{1})", textcoords, arrayIndex ) );
textcoords = texName;
}
string texture = m_texPort.GenerateShaderForOutput( ref dataCollector, texType,false,true );
string scale = m_defaultScale.ToString();
if( m_scalePort.IsConnected )
scale = m_scalePort.GeneratePortInstructions( ref dataCollector );
string viewDirTan = "";
if ( !m_viewdirTanPort.IsConnected )
{
if ( !dataCollector.DirtyNormal )
dataCollector.ForceNormal = true;
if ( dataCollector.IsTemplate )
{
viewDirTan = dataCollector.TemplateDataCollectorInstance.GetTangentViewDir( m_currentPrecisionType );
}
else
{
viewDirTan = GeneratorUtils.GenerateViewDirection( ref dataCollector, UniqueId, ViewSpace.Tangent );
//dataCollector.AddToInput( UniqueId, SurfaceInputs.VIEW_DIR, m_currentPrecisionType );
//viewDirTan = Constants.InputVarStr + "." + UIUtils.GetInputValueFromType( SurfaceInputs.VIEW_DIR );
}
}
else
{
viewDirTan = m_viewdirTanPort.GeneratePortInstructions( ref dataCollector );
}
//generate world normal
string normalWorld = string.Empty;
if ( dataCollector.IsTemplate )
{
normalWorld = dataCollector.TemplateDataCollectorInstance.GetWorldNormal( m_currentPrecisionType );
}
else
{
dataCollector.AddToInput( UniqueId, SurfaceInputs.WORLD_NORMAL, m_currentPrecisionType );
dataCollector.AddToInput( UniqueId, SurfaceInputs.INTERNALDATA, addSemiColon: false );
normalWorld = GeneratorUtils.GenerateWorldNormal( ref dataCollector, UniqueId );
}
//string normalWorld = "WorldNormalVector( " + Constants.InputVarStr + ", float3( 0, 0, 1 ) )";
//generate viewDir in world space
//string worldPos = string.Empty;
//if( dataCollector.IsTemplate )
//{
// worldPos = dataCollector.TemplateDataCollectorInstance.GetWorldPos();
//}
//else
//{
// dataCollector.AddToInput( UniqueId, SurfaceInputs.WORLD_POS );
// worldPos = Constants.InputVarStr + ".worldPos";
//}
//if( !dataCollector.IsTemplate )
// dataCollector.AddToInput( UniqueId, SurfaceInputs.WORLD_POS );
string worldViewDir = GeneratorUtils.GenerateViewDirection( ref dataCollector, UniqueId, ViewSpace.World );
//dataCollector.AddToLocalVariables( UniqueId, m_currentPrecisionType, WirePortDataType.FLOAT3, WorldDirVarStr, TemplateHelperFunctions.WorldSpaceViewDir( dataCollector, worldPos, true ) );
string dx = "ddx("+ textcoords + ")";
string dy = "ddy(" + textcoords + ")";
string refPlane = m_defaultRefPlane.ToString();
if ( m_refPlanePort.IsConnected )
refPlane = m_refPlanePort.GeneratePortInstructions( ref dataCollector );
string curvature = "float2("+ m_CurvatureVector.x + "," + m_CurvatureVector.y + ")";
if ( m_useCurvature )
{
dataCollector.AddToProperties( UniqueId, "[Header(Parallax Occlusion Mapping)]", 300 );
dataCollector.AddToProperties( UniqueId, "_CurvFix(\"Curvature Bias\", Range( 0 , 1)) = 1", 301 );
dataCollector.AddToUniforms( UniqueId, "uniform float _CurvFix;" );
if ( m_curvaturePort.IsConnected )
curvature = m_curvaturePort.GeneratePortInstructions( ref dataCollector );
}
string localVarName = "OffsetPOM" + UniqueId;
dataCollector.AddToUniforms(UniqueId, "uniform float4 "+ texture +"_ST;");
if( m_pomTexType == POMTexTypes.TextureArray )
dataCollector.UsingArrayDerivatives = true;
string functionResult = dataCollector.AddFunctions( m_functionHeader, m_functionBody, ( (m_pomTexType == POMTexTypes.TextureArray) ? "UNITY_Preplaced_TEX2DARRAY(" + texture + ")": texture), textcoords, dx, dy, normalWorld, worldViewDir, viewDirTan, m_minSamples, m_maxSamples, scale, refPlane, texture+"_ST.xy", curvature, arrayIndex );
dataCollector.AddToLocalVariables( UniqueId, m_currentPrecisionType, m_pomUVPort.DataType, localVarName, functionResult );
return GetOutputVectorItem( 0, outputId, localVarName );
}
19
Source : InlineProperty.cs
with GNU General Public License v3.0
from alexismorin
with GNU General Public License v3.0
from alexismorin
public string GetValueOrProperty()
{
if( m_active )
{
PropertyNode node = GetPropertyNode();
if( node != null )
{
return "[" + node.PropertyName + "]";
}
else
{
m_active = false;
m_nodeId = -1;
return m_value.ToString();
}
}
else
{
return m_value.ToString();
}
}
19
Source : InlineProperty.cs
with GNU General Public License v3.0
from alexismorin
with GNU General Public License v3.0
from alexismorin
public string GetValueOrProperty( string defaultValue, bool parentesis = true )
{
if( m_active )
{
PropertyNode node = GetPropertyNode();
if( node != null )
{
if( parentesis )
return "[" + node.PropertyName + "]";
else
return node.PropertyName;
}
else if( !string.IsNullOrEmpty( defaultValue ) )
{
m_active = false;
m_nodeId = -1;
return defaultValue;
}
else
{
m_active = false;
m_nodeId = -1;
return m_value.ToString();
}
}
else
{
return defaultValue;
}
}
19
Source : CustomMaterialInspector.cs
with GNU General Public License v3.0
from alexismorin
with GNU General Public License v3.0
from alexismorin
public override void OnGUI( MaterialEditor materialEditor, MaterialProperty[] properties )
{
IOUtils.Init();
Material mat = materialEditor.target as Material;
if( mat == null )
return;
m_instance = materialEditor;
if( !m_initialized )
{
Init();
m_initialized = true;
Undo.undoRedoPerformed += UndoRedoPerformed;
}
if( Event.current.type == EventType.Repaint &&
mat.HasProperty( IOUtils.DefaultASEDirtyCheckId ) &&
mat.GetInt( IOUtils.DefaultASEDirtyCheckId ) == 1 )
{
mat.SetInt( IOUtils.DefaultASEDirtyCheckId, 0 );
UIUtils.ForceUpdateFromMaterial();
//Event.current.Use();
}
if( materialEditor.isVisible )
{
GUILayout.BeginVertical();
{
GUILayout.Space( 3 );
if( GUILayout.Button( "Open in Shader Editor" ) )
{
AmplifyShaderEditorWindow.LoadMaterialToASE( mat );
}
GUILayout.BeginHorizontal();
{
if( GUILayout.Button( CopyButtonStr ) )
{
Shader shader = mat.shader;
int propertyCount = UnityEditor.ShaderUtil.GetPropertyCount( shader );
string allProperties = string.Empty;
for( int i = 0; i < propertyCount; i++ )
{
UnityEditor.ShaderUtil.ShaderPropertyType type = UnityEditor.ShaderUtil.GetPropertyType( shader, i );
string name = UnityEditor.ShaderUtil.GetPropertyName( shader, i );
string valueStr = string.Empty;
switch( type )
{
case UnityEditor.ShaderUtil.ShaderPropertyType.Color:
{
Color value = mat.GetColor( name );
valueStr = value.r.ToString() + IOUtils.VECTOR_SEPARATOR +
value.g.ToString() + IOUtils.VECTOR_SEPARATOR +
value.b.ToString() + IOUtils.VECTOR_SEPARATOR +
value.a.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Vector:
{
Vector4 value = mat.GetVector( name );
valueStr = value.x.ToString() + IOUtils.VECTOR_SEPARATOR +
value.y.ToString() + IOUtils.VECTOR_SEPARATOR +
value.z.ToString() + IOUtils.VECTOR_SEPARATOR +
value.w.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Float:
{
float value = mat.GetFloat( name );
valueStr = value.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Range:
{
float value = mat.GetFloat( name );
valueStr = value.ToString();
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv:
{
Texture value = mat.GetTexture( name );
valueStr = replacedetDatabase.GetreplacedetPath( value );
Vector2 offset = mat.GetTextureOffset( name );
Vector2 scale = mat.GetTextureScale( name );
valueStr += IOUtils.VECTOR_SEPARATOR + scale.x.ToString() +
IOUtils.VECTOR_SEPARATOR + scale.y.ToString() +
IOUtils.VECTOR_SEPARATOR + offset.x.ToString() +
IOUtils.VECTOR_SEPARATOR + offset.y.ToString();
}
break;
}
allProperties += name + IOUtils.FIELD_SEPARATOR + type + IOUtils.FIELD_SEPARATOR + valueStr;
if( i < ( propertyCount - 1 ) )
{
allProperties += IOUtils.LINE_TERMINATOR;
}
}
EditorPrefs.SetString( IOUtils.MAT_CLIPBOARD_ID, allProperties );
}
if( GUILayout.Button( PasteButtonStr ) )
{
string propertiesStr = EditorPrefs.GetString( IOUtils.MAT_CLIPBOARD_ID, string.Empty );
if( !string.IsNullOrEmpty( propertiesStr ) )
{
string[] propertyArr = propertiesStr.Split( IOUtils.LINE_TERMINATOR );
bool validData = true;
try
{
for( int i = 0; i < propertyArr.Length; i++ )
{
string[] valuesArr = propertyArr[ i ].Split( IOUtils.FIELD_SEPARATOR );
if( valuesArr.Length != 3 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else if( mat.HasProperty( valuesArr[ 0 ] ) )
{
UnityEditor.ShaderUtil.ShaderPropertyType type = (UnityEditor.ShaderUtil.ShaderPropertyType)Enum.Parse( typeof( UnityEditor.ShaderUtil.ShaderPropertyType ), valuesArr[ 1 ] );
switch( type )
{
case UnityEditor.ShaderUtil.ShaderPropertyType.Color:
{
string[] colorVals = valuesArr[ 2 ].Split( IOUtils.VECTOR_SEPARATOR );
if( colorVals.Length != 4 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else
{
mat.SetColor( valuesArr[ 0 ], new Color( Convert.ToSingle( colorVals[ 0 ] ),
Convert.ToSingle( colorVals[ 1 ] ),
Convert.ToSingle( colorVals[ 2 ] ),
Convert.ToSingle( colorVals[ 3 ] ) ) );
}
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Vector:
{
string[] vectorVals = valuesArr[ 2 ].Split( IOUtils.VECTOR_SEPARATOR );
if( vectorVals.Length != 4 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else
{
mat.SetVector( valuesArr[ 0 ], new Vector4( Convert.ToSingle( vectorVals[ 0 ] ),
Convert.ToSingle( vectorVals[ 1 ] ),
Convert.ToSingle( vectorVals[ 2 ] ),
Convert.ToSingle( vectorVals[ 3 ] ) ) );
}
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Float:
{
mat.SetFloat( valuesArr[ 0 ], Convert.ToSingle( valuesArr[ 2 ] ) );
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.Range:
{
mat.SetFloat( valuesArr[ 0 ], Convert.ToSingle( valuesArr[ 2 ] ) );
}
break;
case UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv:
{
string[] texVals = valuesArr[ 2 ].Split( IOUtils.VECTOR_SEPARATOR );
if( texVals.Length != 5 )
{
Debug.LogWarning( "Material clipboard data is corrupted" );
validData = false;
break;
}
else
{
mat.SetTexture( valuesArr[ 0 ], replacedetDatabase.LoadreplacedetAtPath<Texture>( texVals[ 0 ] ) );
mat.SetTextureScale( valuesArr[ 0 ], new Vector2( Convert.ToSingle( texVals[ 1 ] ), Convert.ToSingle( texVals[ 2 ] ) ) );
mat.SetTextureOffset( valuesArr[ 0 ], new Vector2( Convert.ToSingle( texVals[ 3 ] ), Convert.ToSingle( texVals[ 4 ] ) ) );
}
}
break;
}
}
}
}
catch( Exception e )
{
Debug.LogException( e );
validData = false;
}
if( validData )
{
materialEditor.PropertiesChanged();
UIUtils.CopyValuesFromMaterial( mat );
}
else
{
EditorPrefs.SetString( IOUtils.MAT_CLIPBOARD_ID, string.Empty );
}
}
}
}
GUILayout.EndHorizontal();
GUILayout.Space( 5 );
}
GUILayout.EndVertical();
}
EditorGUI.BeginChangeCheck();
//base.OnGUI( materialEditor, properties );
// Draw custom properties instead of calling BASE to use single line texture properties
materialEditor.SetDefaultGUIWidths();
if( m_infoField == null )
{
m_infoField = typeof( MaterialEditor ).GetField( "m_InfoMessage", BindingFlags.Instance | BindingFlags.NonPublic );
}
string info = m_infoField.GetValue( materialEditor ) as string;
if( !string.IsNullOrEmpty( info ) )
{
EditorGUILayout.HelpBox( info, MessageType.Info );
}
else
{
GUIUtility.GetControlID( "EditorTextField".GetHashCode(), FocusType.Preplacedive, new Rect( 0f, 0f, 0f, 0f ) );
}
for( int i = 0; i < properties.Length; i++ )
{
if( ( properties[ i ].flags & ( MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData ) ) == MaterialProperty.PropFlags.None )
{
if( ( properties[ i ].flags & MaterialProperty.PropFlags.NoScaleOffset ) == MaterialProperty.PropFlags.NoScaleOffset )
{
object obj = MaterialPropertyHandlerEx.GetHandler( mat.shader, properties[ i ].name );
if( obj != null )
{
float height = MaterialPropertyHandlerEx.GetPropertyHeight( obj, properties[ i ], properties[ i ].displayName, materialEditor );
//Rect rect = (Rect)materialEditor.GetType().InvokeMember( "GetPropertyRect", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, materialEditor, new object[] { properties[ i ], properties[ i ].displayName, true } );
Rect rect = EditorGUILayout.GetControlRect( true, height, EditorStyles.layerMaskField );
MaterialPropertyHandlerEx.OnGUI( obj, ref rect, properties[ i ], new GUIContent( properties[ i ].displayName ), materialEditor );
if( MaterialPropertyHandlerEx.PropertyDrawer( obj ) != null )
continue;
rect = EditorGUILayout.GetControlRect( true, height, EditorStyles.layerMaskField );
materialEditor.TexturePropertyMiniThumbnail( rect, properties[ i ], properties[ i ].displayName, string.Empty );
}
else
{
materialEditor.TexturePropertySingleLine( new GUIContent( properties[ i ].displayName ), properties[ i ] );
}
}
else
{
float propertyHeight = materialEditor.GetPropertyHeight( properties[ i ], properties[ i ].displayName );
Rect controlRect = EditorGUILayout.GetControlRect( true, propertyHeight, EditorStyles.layerMaskField, new GUILayoutOption[ 0 ] );
materialEditor.ShaderProperty( controlRect, properties[ i ], properties[ i ].displayName );
}
}
}
EditorGUILayout.Space();
materialEditor.RenderQueueField();
#if UNITY_5_6_OR_NEWER
materialEditor.EnableInstancingField();
#endif
#if UNITY_5_6_2 || UNITY_5_6_3 || UNITY_5_6_4 || UNITY_2017_1_OR_NEWER
materialEditor.DoubleSidedGIField();
#endif
materialEditor.LightmapEmissionProperty();
if( m_refreshOnUndo || EditorGUI.EndChangeCheck() )
{
m_refreshOnUndo = false;
string isEmissive = mat.GetTag( "IsEmissive", false, "false" );
if( isEmissive.Equals( "true" ) )
{
mat.globalIlluminationFlags &= (MaterialGlobalIlluminationFlags)3;
}
else
{
mat.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
UIUtils.CopyValuesFromMaterial( mat );
}
if( materialEditor.RequiresConstantRepaint() && m_lastRenderedTime + 0.032999999821186066 < EditorApplication.timeSinceStartup )
{
this.m_lastRenderedTime = EditorApplication.timeSinceStartup;
materialEditor.Repaint();
}
}
19
Source : NaiveMatrix.cs
with MIT License
from altimesh
with MIT License
from altimesh
public void WriteMatrix()
{
for (int k = 0; k < this.Height; ++k)
{
for (int j = 0; j < this.Width; ++j)
{
Console.Write(this[k * this.Width + j].ToString() + " ");
}
Console.WriteLine("");
}
}
19
Source : ModNumberInput.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
protected override void Open()
{
base.Open();
var popup = PopupManager.CreateInputPopup(InputType.Number, Value.ToString());
popup.OnConfirm += OnConfirm;
popup.OnCancel += OnCancel;
}
19
Source : ControlPanel.cs
with MIT License
from AmigoCap
with MIT License
from AmigoCap
public JsonData LoadJson() {
if (Loaded) {
UnloadJson();
}
try {
dataInfo = new FileInfo(selectFile.field.text);
StreamReader r = new StreamReader(selectFile.field.text);
string json = r.ReadToEnd();
data = JsonConvert.DeserializeObject<JsonData>(json);
if (!CheckJsonData(data)) {
throw new System.Exception("Data checking failed");
}
}
catch (System.Exception e) {
MakeErrorWindow("Error while loading .json, make sure it is valid\n\n" + e.Message);
return null;
}
sampling.gameObject.SetActive(true);
axisConf.gameObject.SetActive(true);
spheres.gameObject.SetActive(true);
style.gameObject.SetActive(true);
advanced.gameObject.SetActive(true);
load.interactable = true;
export.interactable = true;
spheres.animate.interactable = false;
spheres.drop.interactable = false;
sampling.randomPaths.isOn = data.randomPaths;
sampling.allPaths.isOn = data.allPaths;
sampling.allInstants.isOn = data.allInstants;
sampling.n_paths.text = data.chosen_n_paths.ToString();
sampling.paths_start.text = data.chosen_paths_start.ToString();
sampling.paths_end.text = data.chosen_paths_end.ToString();
sampling.paths_step.text = data.chosen_paths_step.ToString();
sampling.instants_start.text = data.chosen_instants_start.ToString();
sampling.instants_end.text = data.chosen_instants_end.ToString();
sampling.instants_step.text = data.chosen_instants_step.ToString();
axisConf.gps.isOn = data.useGPSCoords;
Dropdown[] dropdowns = { axisConf.xAxis, axisConf.yAxis, axisConf.zAxis, axisConf.time, style.attribute };
Dropdown.OptionData emptyOption = new Dropdown.OptionData("<no attribute>");
foreach (Dropdown d in dropdowns) {
d.options.Clear();
d.options.Add(emptyOption);
d.value = 0;
d.captionText.text = emptyOption.text;
}
for (int i = 0; i < data.atomAttributes.Length; i++) {
JsonData.AtomAttribute attr = data.atomAttributes[i];
if (attr.name == null || attr.name == "")
attr.name = "unnamed";
Dropdown.OptionData option = new Dropdown.OptionData(attr.name);
foreach (Dropdown d in dropdowns)
d.options.Add(option);
if (attr.name == data.atomAttributeUsedAs_x) {
axisConf.xAxis.value = i + 1;
axisConf.prevValue_x = i + 1;
axisConf.xScale.text = attr.sizeCoeff.ToString();
}
if (attr.name == data.atomAttributeUsedAs_y) {
axisConf.yAxis.value = i + 1;
axisConf.prevValue_y = i + 1;
axisConf.yScale.text = attr.sizeCoeff.ToString();
}
if (attr.name == data.atomAttributeUsedAs_z) {
axisConf.zAxis.value = i + 1;
axisConf.prevValue_z = i + 1;
axisConf.zScale.text = attr.sizeCoeff.ToString();
}
if (attr.name == data.atomAttributeUsedAs_t) {
axisConf.time.value = i + 1;
}
if (attr.name == data.atomAttributeUsedAs_color) {
style.attribute.value = i + 1;
style.startColor.value = (int)attr.colorStart;
style.endColor.value = (int)attr.colorEnd;
style.useMinMax.isOn = attr.valueColorUseMinMax;
style.startValue.text = attr.valueColorStart.ToString();
style.endValue.text = attr.valueColorEnd.ToString();
}
}
spheres.display.isOn = data.spheresDisplay;
spheres.globalTime.text = data.spheresGlobalTime.ToString();
spheres.animSpeed.text = data.spheresAnimSpeed.ToString();
spheres.radius.text = data.spheresRadius.ToString();
advanced.districtSize_x.text = data.districtSize.x.ToString();
advanced.districtSize_y.text = data.districtSize.y.ToString();
advanced.districtSize_z.text = data.districtSize.z.ToString();
advanced.lowerTrunc_x.text = data.lowerTruncature.x.ToString();
advanced.lowerTrunc_y.text = data.lowerTruncature.y.ToString();
advanced.lowerTrunc_z.text = data.lowerTruncature.z.ToString();
advanced.upperTrunc_x.text = data.upperTruncature.x.ToString();
advanced.upperTrunc_y.text = data.upperTruncature.y.ToString();
advanced.upperTrunc_z.text = data.upperTruncature.z.ToString();
_loaded = true;
return data;
}
19
Source : Visualization.cs
with MIT License
from AmigoCap
with MIT License
from AmigoCap
void Update() {
if (!Loaded)
return;
foreach (Path p in paths) {
p.UpdatePath();
}
if (!traceTimeSpheres && old_traceTimeSpheres) {
foreach (Path p in paths) {
foreach (Atom a in p.atoms) {
a.ShouldDisplayBecauseTime = true;
}
}
old_traceTimeSpheres = false;
}
if (displayTimeSpheres) {
if (doSphereDrop) {
DropSpheres();
doSphereDrop = false;
}
if (timeSphereRadius != old_timeSphereRadius) {
foreach (Path p in paths) {
p.UpdateTimeSphereRadius();
}
old_timeSphereRadius = timeSphereRadius;
}
if (traceTimeSpheres && !old_traceTimeSpheres) {
foreach (Path p in paths) {
foreach (Atom a in p.atoms) {
a.ShouldDisplayBecauseTime = false;
}
}
old_traceTimeSpheres = true;
}
Debug.Log("anim: " + doTimeSphereAnimation + "; gtime: " + useGlobalTime + ", " + globalTime);
if (useGlobalTime && doTimeSphereAnimation) {
globalTime += timeSphereAnimationSpeed * Time.deltaTime;
ControlPanel.Instance.spheres.globalTime.text = globalTime.ToString();
}
}
foreach (Path p in paths) {
p.UpdateTimeSphere();
}
if (debugMode) {
if (clearDistrictsToHighlight) {
clearDistrictsToHighlight = false;
foreach (HashSet<int[]> dth in districtsToHighlight) {
dth.Clear();
}
}
}
}
19
Source : Test1.cs
with MIT License
from Aminator
with MIT License
from Aminator
private static void PrintMatrix(float[] array, int width, int height)
{
int numberWidth = array.Max().ToString().Length;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Console.Write(array[x + y * width].ToString().PadLeft(numberWidth));
Console.Write(", ");
}
Console.WriteLine();
}
}
19
Source : DecimalValidationContract.cs
with MIT License
from andrebaltieri
with MIT License
from andrebaltieri
public Contract<T> AreEquals(decimal val, float comparer, string key) =>
AreEquals(val, (decimal)comparer, key, FluntErrorMessages.AreEqualsErrorMessage(val.ToString(), comparer.ToString()));
19
Source : DecimalValidationContract.cs
with MIT License
from andrebaltieri
with MIT License
from andrebaltieri
public Contract<T> AreNotEquals(decimal val, float comparer, string key) =>
AreNotEquals(val, (decimal)comparer, key, FluntErrorMessages.AreNotEqualsErrorMessage(val.ToString(), comparer.ToString()));
19
Source : DoubleValidationContract.cs
with MIT License
from andrebaltieri
with MIT License
from andrebaltieri
public Contract<T> IsGreaterThan(double val, float comparer, string key) =>
IsGreaterThan(val, comparer, key, FluntErrorMessages.IsGreaterThanErrorMessage(key, comparer.ToString()));
See More Examples