Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

4.9 KB
Raw Blame
//! Argument decoding and result encoding for `__native.gpu` (same NaN-box fast path as
//! `crates/webgl/src/args.rs`; duplicated so this crate does not depend on the GL binding).
//!
//! Hot-path calls (writeBuffer, finish, submit) take numbers and typed arrays and nearly every argument is a number. Going
//! through `JSValueToNumber` costs an API lock round-trip per argument, so on 64-bit JavaScriptCore we
//! decode the NaN-boxed `JSValueRef` bits directly (the C API passes encoded `JSValue`s on 64-bit).
//! `calibrate` checks the encoding against the live engine once per page; if anything differs the
//! slow, fully general API path is used instead.
use std::ptr::null_mut;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};

use jsc::*;

static FAST: AtomicBool = AtomicBool::new(false);

const NUMBER_TAG: u64 = 0xfffe_0000_0000_0000;
const DOUBLE_OFFSET: u64 = 1 << 49;
const V_NULL: u64 = 0x02;
const V_FALSE: u64 = 0x06;
const V_TRUE: u64 = 0x07;
const V_UNDEF: u64 = 0x0a;
/// Bits that are zero for a cell (object/string/symbol pointer).
const NOT_CELL_MASK: u64 = NUMBER_TAG | 0x2;

/// Verify the value encoding against the engine (cheap; once per page).
pub fn calibrate(c: Ctx) {
    let enc = |v: JSValueRef| v as u64;
    let ok = unsafe {
        enc(JSValueMakeNumber(c.0, 1.5)) == 1.5f64.to_bits() + DOUBLE_OFFSET
            && enc(JSValueMakeNumber(c.0, -2.25)) == (-2.25f64).to_bits().wrapping_add(DOUBLE_OFFSET)
            && enc(JSValueMakeNumber(c.0, 42.0)) == NUMBER_TAG | 42
            && enc(JSValueMakeNumber(c.0, -7.0)) == NUMBER_TAG | (-7i32 as u32 as u64)
            && enc(JSValueMakeBoolean(c.0, true)) == V_TRUE
            && enc(JSValueMakeBoolean(c.0, false)) == V_FALSE
            && enc(JSValueMakeUndefined(c.0)) == V_UNDEF
            && enc(JSValueMakeNull(c.0)) == V_NULL
            && JSValueToNumber(c.0, (1.5f64.to_bits() + DOUBLE_OFFSET) as JSValueRef, null_mut()) == 1.5
            && JSValueToNumber(c.0, (NUMBER_TAG | 9) as JSValueRef, null_mut()) == 9.0
    };
    FAST.store(ok, Relaxed);
}

#[inline(always)]
fn fast() -> bool {
    FAST.load(Relaxed)
}

/// ToNumber.
#[inline(always)]
pub fn num(c: Ctx, v: Value) -> f64 {
    let u = v.0 as u64;
    if fast() {
        if u >= NUMBER_TAG {
            return (u as u32 as i32) as f64;
        }
        if u & NUMBER_TAG != 0 {
            return f64::from_bits(u.wrapping_sub(DOUBLE_OFFSET));
        }
        match u {
            V_UNDEF => return f64::NAN,
            V_NULL | V_FALSE => return 0.0,
            V_TRUE => return 1.0,
            _ => {}
        }
    }
    unsafe { JSValueToNumber(c.0, v.0, null_mut()) }
}




/// ToBoolean.
#[inline(always)]
pub fn truthy(c: Ctx, v: Value) -> bool {
    let u = v.0 as u64;
    if fast() {
        match u {
            V_TRUE => return true,
            V_FALSE | V_UNDEF | V_NULL => return false,
            _ => {}
        }
        if u >= NUMBER_TAG {
            return u as u32 != 0;
        }
        if u & NUMBER_TAG != 0 {
            let d = f64::from_bits(u.wrapping_sub(DOUBLE_OFFSET));
            return d != 0.0 && !d.is_nan();
        }
    }
    unsafe { JSValueToBoolean(c.0, v.0) }
}


#[inline(always)]
pub fn is_nullish(c: Ctx, v: Value) -> bool {
    let u = v.0 as u64;
    if fast() {
        return u == V_NULL || u == V_UNDEF;
    }
    v.is_nullish(c)
}

/// The bytes viewed by an `ArrayBufferView` (typed array or DataView). The JS layer only ever
/// passes views here; anything else yields `None`. Valid until the next call into JavaScriptCore.
#[inline]
pub fn view<'a>(c: Ctx, v: Value) -> Option<&'a mut [u8]> {
    let u = v.0 as u64;
    let is_cell = if fast() { u != 0 && u & NOT_CELL_MASK == 0 } else { v.is_object(c) };
    if !is_cell {
        return None;
    }
    unsafe {
        let o = v.0 as JSObjectRef;
        let p = JSObjectGetTypedArrayBytesPtr(c.0, o, null_mut()) as *mut u8;
        let len = JSObjectGetTypedArrayByteLength(c.0, o, null_mut());
        if p.is_null() {
            return if len == 0 { Some(&mut []) } else { None };
        }
        let off = JSObjectGetTypedArrayByteOffset(c.0, o, null_mut());
        Some(std::slice::from_raw_parts_mut(p.add(off), len))
    }
}

#[inline(always)]
pub fn int_val(c: Ctx, n: i32) -> Value {
    if fast() { Value((NUMBER_TAG | n as u32 as u64) as JSValueRef) } else { c.num(n as f64) }
}

#[inline]
pub fn num_val(c: Ctx, d: f64) -> Value {
    if fast() {
        if d >= -2147483648.0 && d <= 2147483647.0 && d == (d as i32) as f64 && !(d == 0.0 && d.is_sign_negative()) {
            return int_val(c, d as i32);
        }
        let bits = if d.is_nan() { 0x7ff8_0000_0000_0000u64 } else { d.to_bits() };
        return Value(bits.wrapping_add(DOUBLE_OFFSET) as JSValueRef);
    }
    c.num(d)
}


#[inline(always)]
pub fn undef(c: Ctx) -> Value {
    if fast() { Value(V_UNDEF as JSValueRef) } else { c.undefined() }
}

#[inline(always)]
pub fn null(c: Ctx) -> Value {
    if fast() { Value(V_NULL as JSValueRef) } else { c.null() }
}