Portal belajar membuat aplikasi Augmented Reality dan Virtual Reality

Minggu, 05 Juni 2022

Displaying Player Name - Normcore

23.12 Posted by Dicky Rachmat Iskandar No comments

Buat script AvatarAttributesModel

lalu Compile Model di inspector


using Normal.Realtime;

using Normal.Realtime.Serialization;


[RealtimeModel]

public partial class AvatarAttributesModel

{

    [RealtimeProperty(1, true, true)]

    private string _nickname;

}


Senin, 20 Desember 2021

Iframe test

05.33 Posted by Dicky Rachmat Iskandar No comments

 

Selasa, 19 Oktober 2021

Selasa, 18 Mei 2021

Vuforia Cloud Add Target From Unity

07.07 Posted by Dicky Rachmat Iskandar No comments

 Firstly, you should download a Json dll library that support for serialize a data for upload to the server. JsonFx.Json and learn a little bit about a structure from Vuforia Web Services , Vuforia example

Secondly, copy the code below, and drag image to the code for new texture. AddYour Key and build.

public class PostNewTrackableRequest
{
    public string name;
    public float width;
    public string image;
    public string application_metadata;
}

public class CloudUpLoading : MonoBehaviour 
{

 public Texture2D texture;

 private string access_key = "Your Server Access Key";
 private string secret_key = "Your Server Secret Key";
 private string url = @"https://vws.vuforia.com";
 private string targetName = "MyTarget"; // must change when upload another Image Target, avoid same as exist Image on cloud

 private byte[] requestBytesArray;

 public void CallPostTarget()
 {
     StartCoroutine (PostNewTarget());
 }

 IEnumerator PostNewTarget()
 {

     string requestPath = "/targets";
     string serviceURI = url + requestPath;
     string httpAction = "POST";
     string contentType = "application/json";
     string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime()); 
 
     Debug.Log(date);
 
     // if your texture2d has RGb24 type, don't need to redraw new texture2d
     Texture2D tex = new Texture2D(texture.width,texture.height,TextureFormat.RGB24,false);
     tex.SetPixels(texture.GetPixels());
     tex.Apply();
     byte[] image = tex.EncodeToPNG();
 
     string metadataStr = "Vuforia metadata";//May use for key,name...in game
     byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);
     PostNewTrackableRequest model = new PostNewTrackableRequest();
     model.name = targetName;
     model.width = 64.0f; // don't need same as width of texture
     model.image = System.Convert.ToBase64String(image);
 
     model.application_metadata = System.Convert.ToBase64String(metadata);
     string requestBody = JsonWriter.Serialize(model);

     WWWForm form = new WWWForm ();

     var headers = form.headers;
     byte[] rawData = form.data;
     headers[ "Host"]=url;
     headers["Date"] = date;
     headers["Content-Type"]= contentType;

     HttpWebRequest httpWReq = (HttpWebRequest)HttpWebRequest.Create(serviceURI);
 
     MD5 md5 = MD5.Create();
     var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     for (int i = 0; i < contentMD5bytes.Length; i++)
     {
         sb.Append(contentMD5bytes[i].ToString("x2"));
     }
 
     string contentMD5 = sb.ToString();
 
     string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);
 
     HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key));
     byte[] sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
     MemoryStream stream = new MemoryStream(sha1Bytes);
     byte[] sha1Hash = sha1.ComputeHash(stream);
     string signature = System.Convert.ToBase64String(sha1Hash);

     headers["Authorization"]=string.Format("VWS {0}:{1}", access_key, signature);
 
     Debug.Log("<color=green>Signaturere+"</color>");

     WWW request =new WWW(serviceURI,System.Text.Encoding.UTF8.GetBytes(JsonWriter.Serialize(model)), headers);
     yield return request;

     if (request.error != null)
     {
         Debug.Log("requestr: " + request.error);
     }
     else
     {
         Debug.Log("requestess");
         Debug.Log("returned" + request.data);
     }

 }
}

Jumat, 28 Agustus 2020

JnuUtil.cs

15.48 Posted by Dicky Rachmat Iskandar No comments


https://markcastle.com/steps-to-create-a-native-android-plugin-for-unity-in-java-using-android-studio-part-2-of-2/

https://gist.github.com/markcastle/a1530efd5278607862fec09df89e59db 

/*
Copyright 2017 Captive Reality Ltd
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is
hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Source:
Description:
A very simple static helper (for Unity) that you can use to call a static Java method in a Java class using Jni
Examples:
int result = CaptiveReality.Jni.Util.StaticCall<int>("getAMethodWhichReturnsInt", 1, "com.yourandroidlib.example.ClassName");
string result = CaptiveReality.Jni.Util.StaticCall<string>("getAMethodWhichReturnsString", "UNKNOWN", "com.yourandroidlib.example.ClassName");
*/
using UnityEngine;
namespace CaptiveReality.Jni
{
class Util
{
/// <summary>
/// StaticCall - Call a static Java method in a class using Jni
/// </summary>
/// <typeparam name="T">The return type of the method in the class you are calling</typeparam>
/// <param name="methodName">The name of the method you want to call</param>
/// <param name="defaultValue">The value you want to return if there was a problem</param>
/// <param name="androidJavaClass">The name of the Package and Class eg, packagename.myClassName or com.yourandroidlib.example.ClassName</param>
/// <returns>Generic</returns>
public static T StaticCall<T>(string methodName, T defaultValue, string androidJavaClass)
{
T result;
// Only works on Android!
if (Application.platform != RuntimePlatform.Android)
{
return defaultValue;
}
try
{
using (AndroidJavaClass androidClass = new AndroidJavaClass(androidJavaClass))
{
if (null != androidClass)
{
result = androidClass.CallStatic<T>(methodName);
}
else
{
result = defaultValue;
}
}
}
catch (System.Exception ex)
{
// If there is an exception, do nothing but return the default value
// Uncomment this to see exceptions in Unity Debug Log....
// UnityEngine.Debug.Log(string.Format("{0}.{1} Exception:{2}", androidJavaClass, methodName, ex.ToString() ));
return defaultValue;
}
return result;
}
}
} Call FROM JNI
using UnityEngine;
using UnityEngine.UI;
 
public class HelloWorld : MonoBehaviour {
 
    Text textObj;
 
    void Start () {
 
        // Find the Text UI object attached to the game object this script is attached to
        textObj = gameObject.GetComponent();
 
        // Make the call using JNI to the Java Class and write out the response (or write 'Invalid Response From JNI' if there was a problem).
        textObj.text = CaptiveReality.Jni.Util.StaticCall("sayHello", "Invalid Response From JNI", "com.captivereality.texturehelper.HelloWorld");
    }
    
}

Senin, 17 Februari 2020

Sent email from unity with image attachment

09.01 Posted by Dicky Rachmat Iskandar No comments
UNITY

using System.Collections;
using UnityEngine.Networking;
using UnityEngine;

public class EmailController: MonoBehaviour
{
    public string email = "reciever@mail.com";
    public string screenShotURL = "https://www.your-domain.com/upload.php";

    void Start()
    {
       //sending email when start
        StartCoroutine(UploadPNG());
    }

    IEnumerator UploadPNG()
    {
        // We should only read the screen after all rendering is complete
        yield return new WaitForEndOfFrame();

        // Create a texture the size of the screen, RGB24 format
        int width = Screen.width;
        int height = Screen.height;
        var tex = new Texture2D(width, height, TextureFormat.RGB24, false);

        // Read screen contents into the texture
        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        tex.Apply();

        // Encode texture into PNG
        byte[] bytes = tex.EncodeToPNG();
        Destroy(tex);

        // Create a Web Form
        WWWForm form = new WWWForm();
        form.AddField("name", email);
        form.AddBinaryData("fileToUpload", bytes, "ScreenShot.png", "image/png");

        // Upload to a cgi script
        using (var w = UnityWebRequest.Post(screenShotURL, form))
        {
            yield return w.SendWebRequest();
            if (w.isNetworkError || w.isHttpError)
            {
                print(w.error);
            }
            else
            {
                print(w.uploadHandler);
            }
        }
    }
}


Senin, 04 November 2019

VR- Unity Rotate Camera by Gyroscope and Touch Swipe

22.05 Posted by Dicky Rachmat Iskandar No comments
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GyroscopeCameraRotation : BasicCameraRotation
{
    private float x;
    private float y;

    public bool gyroEnabled = false;
    readonly float sensitivity = 50.0f;

    private Gyroscope gyro;

    void Start()
    {
        gyroEnabled = EnableGyro();
    }

    private bool EnableGyro()
    {
        if (SystemInfo.supportsGyroscope)
        {
            gyro = Input.gyro;
            gyro.enabled = true;
            return true;
        }

        return false;
    }
    void Update()
    {
        if (gyroEnabled)
        {
            GyroRotation();
        }
    }
    void GyroRotation()
    {
        x = Input.gyro.rotationRate.x;
        y = Input.gyro.rotationRate.y;

        float xFiltered = FilterGyroValues(x);
        RotateUpDown(xFiltered * sensitivity);

        float yFiltered = FilterGyroValues(y);
        RotateRightLeft(yFiltered * sensitivity);
    }

    float FilterGyroValues(float axis)
    {
        if (axis < -0.1 || axis > 0.1)
        {
            return axis;
        }
        else
        {
            return 0;
        }
    }
}

public class SpinWheelScript : BasicCameraRotation
{
    Vector3 firstPoint;
    float sensitivity = 2.5f;

    void Update()
    {
        TouchRotation();
    }
    void TouchRotation()
    {
        if (Input.touchCount > 0)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                firstPoint = Input.GetTouch(0).position;
            }
            if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                Vector3 secondPoint = Input.GetTouch(0).position;

                float x = FilterGyroValues(secondPoint.x - firstPoint.x);
                RotateRightLeft(x * sensitivity);

                float y = FilterGyroValues(secondPoint.y - firstPoint.y);
                RotateUpDown(y * -sensitivity);

                firstPoint = secondPoint;
            }
        }
    }
    float FilterGyroValues(float axis)
    {
        float thresshold = 0.5f;
        if (axis < -thresshold || axis > thresshold)
        {
            return axis;
        }
        else
        {
            return 0;
        }
    }
}

public class BasicCameraRotation : MonoBehaviour
{
    //Rotasi ke Atas & Bawah
    public void RotateUpDown(float axis)
    {
        transform.RotateAround(transform.position, transform.right, -axis * Time.deltaTime);
    }

    //Rotasi Ke Kanan & Kiri
    public void RotateRightLeft(float axis)
    {
        transform.RotateAround(transform.position, Vector3.up, -axis * Time.deltaTime);
    }
}