Example #1
0
already_AddRefed<AudioBuffer>
AudioContext::CreateBuffer(JSContext* aJSContext, const ArrayBuffer& aBuffer,
                          bool aMixToMono, ErrorResult& aRv)
{
  // Do not accept this method unless the legacy pref has been set.
  if (!Preferences::GetBool("media.webaudio.legacy.AudioContext")) {
    aRv.ThrowNotEnoughArgsError();
    return nullptr;
  }

  // Sniff the content of the media.
  // Failed type sniffing will be handled by SyncDecodeMedia.
  nsAutoCString contentType;
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, nullptr,
                  aBuffer.Data(), aBuffer.Length(),
                  contentType);

  nsRefPtr<WebAudioDecodeJob> job =
    new WebAudioDecodeJob(contentType, this, aBuffer);

  if (mDecoder.SyncDecodeMedia(contentType.get(),
                               aBuffer.Data(), aBuffer.Length(), *job) &&
      job->mOutput) {
    nsRefPtr<AudioBuffer> buffer = job->mOutput.forget();
    if (aMixToMono) {
      buffer->MixToMono(aJSContext);
    }
    return buffer.forget();
  }

  return nullptr;
}
void
PresentationConnection::Send(const ArrayBuffer& aData,
                             ErrorResult& aRv)
{
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send message due to an internal error."));
    return;
  }

  aData.ComputeLengthAndData();

  static_assert(sizeof(*aData.Data()) == 1, "byte-sized data required");

  uint32_t length = aData.Length();
  char* data = reinterpret_cast<char*>(aData.Data());
  nsDependentCSubstring msgString(data, length);

  nsresult rv = service->SendSessionBinaryMsg(mId, mRole, msgString);
  if(NS_WARN_IF(NS_FAILED(rv))) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send binary message for ArrayBuffer message."));
  }
}
Example #3
0
already_AddRefed<AudioBuffer>
AudioContext::CreateBuffer(JSContext* aJSContext, ArrayBuffer& aBuffer,
                          bool aMixToMono, ErrorResult& aRv)
{
  // Sniff the content of the media.
  // Failed type sniffing will be handled by SyncDecodeMedia.
  nsAutoCString contentType;
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, nullptr,
                  aBuffer.Data(), aBuffer.Length(),
                  contentType);

  WebAudioDecodeJob job(contentType, this);

  if (mDecoder.SyncDecodeMedia(contentType.get(),
                               aBuffer.Data(), aBuffer.Length(), job) &&
      job.mOutput) {
    nsRefPtr<AudioBuffer> buffer = job.mOutput.forget();
    if (aMixToMono) {
      buffer->MixToMono(aJSContext);
    }
    return buffer.forget();
  }

  return nullptr;
}
Example #4
0
    Var AsmJsChangeHeapBuffer(RecyclableObject * function, CallInfo callInfo, ...)
    {
        PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);

        ARGUMENTS(args, callInfo);
        ScriptContext* scriptContext = function->GetScriptContext();

        Assert(!(callInfo.Flags & CallFlags_New));

        if (args.Info.Count < 1 || !ArrayBuffer::Is(args[1]))
        {
            JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject);
        }


        ArrayBuffer* newArrayBuffer = ArrayBuffer::FromVar(args[1]);
        if (newArrayBuffer->IsDetached() || newArrayBuffer->GetByteLength() & 0xffffff || newArrayBuffer->GetByteLength() <= 0xffffff || newArrayBuffer->GetByteLength() > 0x80000000)
        {
            return JavascriptBoolean::ToVar(FALSE, scriptContext);
        }
        FrameDisplay* frame = ((ScriptFunction*)function)->GetEnvironment();
        Var* moduleArrayBuffer = (Var*)frame->GetItem(0) + AsmJsModuleMemory::MemoryTableBeginOffset;
        *moduleArrayBuffer = newArrayBuffer;
        return JavascriptBoolean::ToVar(TRUE, scriptContext);
    }
ThreadableWebSocketChannel::SendResult WorkerThreadableWebSocketChannel::Bridge::send(const ArrayBuffer& binaryData, unsigned byteOffset, unsigned byteLength)
{
    if (!m_workerClientWrapper || !m_peer)
        return ThreadableWebSocketChannel::SendFail;

    // ArrayBuffer isn't thread-safe, hence the content of ArrayBuffer is copied into Vector<char>.
    Vector<char>* dataPtr = std::make_unique<Vector<char>>(byteLength).release();
    if (binaryData.byteLength())
        memcpy(dataPtr->data(), static_cast<const char*>(binaryData.data()) + byteOffset, byteLength);
    setMethodNotCompleted();

    Peer* peer = m_peer;
    m_loaderProxy.postTaskToLoader([peer, dataPtr] (ScriptExecutionContext& context) {
        ASSERT(isMainThread());
        ASSERT_UNUSED(context, context.isDocument());
        ASSERT(peer);

        std::unique_ptr<Vector<char>> data(dataPtr);
        RefPtr<ArrayBuffer> arrayBuffer = ArrayBuffer::create(data->data(), data->size());
        peer->send(*arrayBuffer);
    });

    Ref<Bridge> protect(*this);
    waitForMethodCompletion();
    ThreadableWebSocketChannelClientWrapper* clientWrapper = m_workerClientWrapper.get();
    if (!clientWrapper)
        return ThreadableWebSocketChannel::SendFail;
    return clientWrapper->sendRequestResult();
}
Example #6
0
Js::Var CreateBuffer(const uint8* buf, uint size, void* user_data)
{
    Context* ctx = (Context*)user_data;
    ArrayBuffer* arrayBuffer = ctx->scriptContext->GetLibrary()->CreateArrayBuffer(size);
    js_memcpy_s(arrayBuffer->GetBuffer(), arrayBuffer->GetByteLength(), buf, size);
    return arrayBuffer;
}
Example #7
0
void
AudioContext::DecodeAudioData(const ArrayBuffer& aBuffer,
                              DecodeSuccessCallback& aSuccessCallback,
                              const Optional<OwningNonNull<DecodeErrorCallback> >& aFailureCallback)
{
  AutoJSAPI jsapi;
  jsapi.Init();
  JSContext* cx = jsapi.cx();
  JSAutoCompartment ac(cx, aBuffer.Obj());

  aBuffer.ComputeLengthAndData();

  // Neuter the array buffer
  size_t length = aBuffer.Length();
  JS::RootedObject obj(cx, aBuffer.Obj());

  uint8_t* data = static_cast<uint8_t*>(JS_StealArrayBufferContents(cx, obj));

  // Sniff the content of the media.
  // Failed type sniffing will be handled by AsyncDecodeMedia.
  nsAutoCString contentType;
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, nullptr, data, length, contentType);

  nsRefPtr<DecodeErrorCallback> failureCallback;
  if (aFailureCallback.WasPassed()) {
    failureCallback = &aFailureCallback.Value();
  }
  nsRefPtr<WebAudioDecodeJob> job(
    new WebAudioDecodeJob(contentType, this,
                          &aSuccessCallback, failureCallback));
  mDecoder.AsyncDecodeMedia(contentType.get(), data, length, *job);
  // Transfer the ownership to mDecodeJobs
  mDecodeJobs.AppendElement(job);
}
// Constructor of BluetoothGattDescriptor in ATT server role
BluetoothGattDescriptor::BluetoothGattDescriptor(
  nsPIDOMWindow* aOwner,
  BluetoothGattCharacteristic* aCharacteristic,
  const nsAString& aDescriptorUuid,
  const GattPermissions& aPermissions,
  const ArrayBuffer& aValue)
  : mOwner(aOwner)
  , mCharacteristic(aCharacteristic)
  , mUuidStr(aDescriptorUuid)
  , mPermissions(BLUETOOTH_EMPTY_GATT_ATTR_PERM)
  , mAttRole(ATT_SERVER_ROLE)
  , mActive(false)
{
  MOZ_ASSERT(aOwner);
  MOZ_ASSERT(aCharacteristic);

  // UUID
  memset(&mDescriptorId, 0, sizeof(mDescriptorId));
  StringToUuid(aDescriptorUuid, mDescriptorId.mUuid);

  // permissions
  GattPermissionsToBits(aPermissions, mPermissions);

  // value
  aValue.ComputeLengthAndData();
  mValue.AppendElements(aValue.Data(), aValue.Length());
}
already_AddRefed<Promise>
BluetoothGattCharacteristic::WriteValue(const ArrayBuffer& aValue,
                                        ErrorResult& aRv)
{
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
  if (!global) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsRefPtr<Promise> promise = Promise::Create(global, aRv);
  NS_ENSURE_TRUE(!aRv.Failed(), nullptr);

  BT_ENSURE_TRUE_REJECT(mProperties &
                          (GATT_CHAR_PROP_BIT_WRITE_NO_RESPONSE |
                           GATT_CHAR_PROP_BIT_WRITE |
                           GATT_CHAR_PROP_BIT_SIGNED_WRITE),
                        promise,
                        NS_ERROR_NOT_AVAILABLE);

  aValue.ComputeLengthAndData();

  nsTArray<uint8_t> value;
  value.AppendElements(aValue.Data(), aValue.Length());

  BluetoothService* bs = BluetoothService::Get();
  BT_ENSURE_TRUE_REJECT(bs, promise, NS_ERROR_NOT_AVAILABLE);

  bs->GattClientWriteCharacteristicValueInternal(
    mService->GetAppUuid(), mService->GetServiceId(),
    mCharId, mWriteType, value,
    new BluetoothVoidReplyRunnable(nullptr, promise));

  return promise.forget();
}
Example #10
0
void
SourceBuffer::AppendBuffer(const ArrayBuffer& aData, ErrorResult& aRv)
{
  MOZ_ASSERT(NS_IsMainThread());
  MSE_API("AppendBuffer(ArrayBuffer)");
  aData.ComputeLengthAndData();
  AppendData(aData.Data(), aData.Length(), aRv);
}
Example #11
0
/* static */ bool
PushUtil::CopyArrayBufferToArray(const ArrayBuffer& aBuffer,
                                 nsTArray<uint8_t>& aArray)
{
  aBuffer.ComputeLengthAndData();
  return aArray.SetLength(aBuffer.Length(), fallible) &&
         aArray.ReplaceElementsAt(0, aBuffer.Length(), aBuffer.Data(),
                                  aBuffer.Length(), fallible);
}
Example #12
0
already_AddRefed<Promise>
AudioContext::DecodeAudioData(const ArrayBuffer& aBuffer,
                              const Optional<OwningNonNull<DecodeSuccessCallback> >& aSuccessCallback,
                              const Optional<OwningNonNull<DecodeErrorCallback> >& aFailureCallback,
                              ErrorResult& aRv)
{
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());
  RefPtr<Promise> promise;
  AutoJSAPI jsapi;
  jsapi.Init();
  JSContext* cx = jsapi.cx();
  JSAutoCompartment ac(cx, aBuffer.Obj());

  promise = Promise::Create(parentObject, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  aBuffer.ComputeLengthAndData();

  if (aBuffer.IsShared()) {
    // Throw if the object is mapping shared memory (must opt in).
    aRv.ThrowTypeError<MSG_TYPEDARRAY_IS_SHARED>(NS_LITERAL_STRING("Argument of AudioContext.decodeAudioData"));
    return nullptr;
  }

  // Detach the array buffer
  size_t length = aBuffer.Length();
  JS::RootedObject obj(cx, aBuffer.Obj());

  uint8_t* data = static_cast<uint8_t*>(JS_StealArrayBufferContents(cx, obj));

  // Sniff the content of the media.
  // Failed type sniffing will be handled by AsyncDecodeWebAudio.
  nsAutoCString contentType;
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, nullptr, data, length, contentType);

  RefPtr<DecodeErrorCallback> failureCallback;
  RefPtr<DecodeSuccessCallback> successCallback;
  if (aFailureCallback.WasPassed()) {
    failureCallback = &aFailureCallback.Value();
  }
  if (aSuccessCallback.WasPassed()) {
    successCallback = &aSuccessCallback.Value();
  }
  RefPtr<WebAudioDecodeJob> job(
    new WebAudioDecodeJob(contentType, this,
                          promise, successCallback, failureCallback));
  AsyncDecodeWebAudio(contentType.get(), data, length, *job);
  // Transfer the ownership to mDecodeJobs
  mDecodeJobs.AppendElement(job.forget());

  return promise.forget();
}
	void unpinArrays() {
		// check if no real array arguments and if so, unpin our dummyArray 
		if (arrayBufs.size() == 0) {
			okraContextHolder->dummyArrayBuf->unpinCommit(jenv);
		}
		else {
			for (int i=0; i<arrayBufs.size(); i++) {
				ArrayBuffer *arrayBuffer = arrayBufs.at(i);
				arrayBuffer->unpinCommit(jenv);
			}
		}
	}
static v8::Handle<v8::Value> sliceCallback(const v8::Arguments& args)
{
    if (args.Length() < 1)
        return throwNotEnoughArgumentsError(args.GetIsolate());
    ArrayBuffer* imp = V8ArrayBuffer::toNative(args.Holder());
    V8TRYCATCH(int, begin, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
    if (args.Length() <= 1) {
        return toV8(imp->slice(begin), args.Holder(), args.GetIsolate());
    }
    V8TRYCATCH(int, end, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
    return toV8(imp->slice(begin, end), args.Holder(), args.GetIsolate());
}
Example #15
0
void
nsDOMDataChannel::Send(const ArrayBuffer& aData, ErrorResult& aRv)
{
  NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");

  MOZ_ASSERT(sizeof(*aData.Data()) == 1);
  uint32_t len = aData.Length();
  char* data = reinterpret_cast<char*>(aData.Data());

  nsDependentCSubstring msgString(data, len);
  Send(nullptr, msgString, len, true, aRv);
}
WebSocketChannel::SendResult WorkerThreadableWebSocketChannel::Bridge::send(const ArrayBuffer& binaryData, unsigned byteOffset, unsigned byteLength)
{
    if (!m_workerClientWrapper || !m_workerGlobalScope)
        return WebSocketChannel::SendFail;
    ASSERT(m_syncHelper);
    // ArrayBuffer isn't thread-safe, hence the content of ArrayBuffer is copied into Vector<char>.
    OwnPtr<Vector<char> > data = adoptPtr(new Vector<char>(byteLength));
    if (binaryData.byteLength())
        memcpy(data->data(), static_cast<const char*>(binaryData.data()) + byteOffset, byteLength);
    m_loaderProxy.postTaskToLoader(CallClosureTask::create(bind(&Peer::sendArrayBuffer, m_peer, data.release())));
    RefPtr<Bridge> protect(this);
    waitForMethodCompletion();
    return m_syncHelper->sendRequestResult();
}
Example #17
0
void
nsDOMDataChannel::Send(const ArrayBuffer& aData, ErrorResult& aRv)
{
  MOZ_ASSERT(NS_IsMainThread(), "Not running on main thread");

  aData.ComputeLengthAndData();

  static_assert(sizeof(*aData.Data()) == 1, "byte-sized data required");

  uint32_t len = aData.Length();
  char* data = reinterpret_cast<char*>(aData.Data());

  nsDependentCSubstring msgString(data, len);
  Send(nullptr, msgString, len, true, aRv);
}
Example #18
0
already_AddRefed<Promise>
AudioContext::DecodeAudioData(const ArrayBuffer& aBuffer,
                              const Optional<OwningNonNull<DecodeSuccessCallback> >& aSuccessCallback,
                              const Optional<OwningNonNull<DecodeErrorCallback> >& aFailureCallback)
{
  ErrorResult rv;
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());
  nsRefPtr<Promise> promise;
  AutoJSAPI jsapi;
  jsapi.Init();
  JSContext* cx = jsapi.cx();
  JSAutoCompartment ac(cx, aBuffer.Obj());

  promise = Promise::Create(parentObject, rv);
  if (rv.Failed()) {
    return nullptr;
  }

  aBuffer.ComputeLengthAndData();

  // Neuter the array buffer
  size_t length = aBuffer.Length();
  JS::RootedObject obj(cx, aBuffer.Obj());

  uint8_t* data = static_cast<uint8_t*>(JS_StealArrayBufferContents(cx, obj));

  // Sniff the content of the media.
  // Failed type sniffing will be handled by AsyncDecodeMedia.
  nsAutoCString contentType;
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, nullptr, data, length, contentType);

  nsRefPtr<DecodeErrorCallback> failureCallback;
  nsRefPtr<DecodeSuccessCallback> successCallback;
  if (aFailureCallback.WasPassed()) {
    failureCallback = &aFailureCallback.Value();
  }
  if (aSuccessCallback.WasPassed()) {
    successCallback = &aSuccessCallback.Value();
  }
  nsRefPtr<WebAudioDecodeJob> job(
    new WebAudioDecodeJob(contentType, this,
                          promise, successCallback, failureCallback));
  mDecoder.AsyncDecodeMedia(contentType.get(), data, length, *job);
  // Transfer the ownership to mDecodeJobs
  mDecodeJobs.AppendElement(job.forget());

  return promise.forget();
}
Example #19
0
ThreadableWebSocketChannel::SendResult WebSocketChannel::send(const ArrayBuffer& binaryData, unsigned byteOffset, unsigned byteLength)
{
    LOG(Network, "WebSocketChannel %p send() Sending ArrayBuffer %p byteOffset=%u byteLength=%u", this, &binaryData, byteOffset, byteLength);
    enqueueRawFrame(WebSocketFrame::OpCodeBinary, static_cast<const char*>(binaryData.data()) + byteOffset, byteLength);
    processOutgoingFrameQueue();
    return ThreadableWebSocketChannel::SendSuccess;
}
Example #20
0
void OsiIF::_addCols(ArrayBuffer<Column*> &newCols)
{
	CoinPackedVector *newcol = new CoinPackedVector;

	for (int i = 0; i < newCols.size(); i++) {
		int num = newCols[i]->nnz();
		double ub =  newCols[i]->uBound();
		double lb =  newCols[i]->lBound();
		double obj =  newCols[i]->obj();
		int *supports = new int[num]; //!< supports of added rows
		double  *coeffs = new double[num]; //!< coefficients of added rows

		for (int j = 0; j < num; j++) {
			supports[j] = newCols[i]->support(j);
			coeffs[j] = newCols[i]->coeff(j);
		}

		newcol->setVector(num, supports, coeffs);
		lpSolverTime_.start();
		osiLP_->addCol(*newcol, lb, ub, obj);
		lpSolverTime_.stop();

		freeInt(supports);
		freeDouble(coeffs);
	}

	lpSolverTime_.start();
	numCols_ = osiLP_->getNumCols();
	collower_ = osiLP_->getColLower();
	colupper_ = osiLP_->getColUpper();
	objcoeff_ = osiLP_->getObjCoefficients();
	lpSolverTime_.stop();
	delete newcol;
}
bool WorkerThreadableWebSocketChannel::Bridge::send(const ArrayBuffer& binaryData)
{
    if (!m_workerClientWrapper)
        return false;
    ASSERT(m_peer);
    // ArrayBuffer isn't thread-safe, hence the content of ArrayBuffer is copied into Vector<char>.
    OwnPtr<Vector<char> > data = adoptPtr(new Vector<char>(binaryData.byteLength()));
    if (binaryData.byteLength())
        memcpy(data->data(), binaryData.data(), binaryData.byteLength());
    setMethodNotCompleted();
    m_loaderProxy.postTaskToLoader(createCallbackTask(&WorkerThreadableWebSocketChannel::mainThreadSendArrayBuffer, AllowCrossThreadAccess(m_peer), data.release()));
    RefPtr<Bridge> protect(this);
    waitForMethodCompletion();
    ThreadableWebSocketChannelClientWrapper* clientWrapper = m_workerClientWrapper.get();
    return clientWrapper && clientWrapper->sendRequestResult();
}
Example #22
0
bool WebSocketChannel::send(const ArrayBuffer& binaryData)
{
    LOG(Network, "WebSocketChannel %p send arraybuffer %p", this, &binaryData);
    ASSERT(!m_useHixie76Protocol);
    enqueueRawFrame(WebSocketFrame::OpCodeBinary, static_cast<const char*>(binaryData.data()), binaryData.byteLength());
    return true;
}
Example #23
0
// static
already_AddRefed<nsIInputStream>
FileHandleBase::GetInputStream(const ArrayBuffer& aValue,
                               uint64_t* aInputLength, ErrorResult& aRv)
{
  aValue.ComputeLengthAndData();
  const char* data = reinterpret_cast<const char*>(aValue.Data());
  uint32_t length = aValue.Length();

  nsCOMPtr<nsIInputStream> stream;
  aRv = NS_NewByteInputStream(getter_AddRefs(stream), data, length,
                              NS_ASSIGNMENT_COPY);
  if (aRv.Failed()) {
    return nullptr;
  }

  *aInputLength = length;
  return stream.forget();
}
Example #24
0
void LpSub::constraint2row(
	ArrayBuffer<Constraint*> &cons,
	ArrayBuffer<Row*> &rows)
{
	int   conNnz;                      //!< number of nonzero elements in constraint
	Row   rowBuf(master_, sub_->nVar());  //!< dummy to generate row
	Row  *row;                         //!< pointer to the new row

	const int nCons = cons.size();

	for (int c = 0; c < nCons; c++) {
		conNnz = cons[c]->genRow(sub_->actVar(), rowBuf);
		row = new Row(master_, conNnz);
		row->copy(rowBuf);
		rows.push(row);
		rowBuf.clear();
	}
}
Example #25
0
nsresult
TCPSocketChild::SendSend(const ArrayBuffer& aData,
                         uint32_t aByteOffset,
                         uint32_t aByteLength,
                         uint32_t aTrackingNumber)
{
  uint32_t buflen = aData.Length();
  uint32_t offset = std::min(buflen, aByteOffset);
  uint32_t nbytes = std::min(buflen - aByteOffset, aByteLength);
  FallibleTArray<uint8_t> fallibleArr;
  if (!fallibleArr.InsertElementsAt(0, aData.Data() + offset, nbytes, fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  InfallibleTArray<uint8_t> arr;
  arr.SwapElements(fallibleArr);
  SendData(arr, aTrackingNumber);
  return NS_OK;
}
	void pinArrays() {
		// if no real array arguments, use our dummyArray arg so we can pin something
		if (arrayBufs.size() == 0) {
			okraContextHolder->dummyArrayBuf->pin(jenv);
		}
		else {
			for (int i=0; i<arrayBufs.size(); i++) {
				ArrayBuffer *arrayBuffer = arrayBufs.at(i);
				// FIXME, should be logic here to check for movement?
				if (!arrayBuffer->isPinned) {
					arrayBuffer->pin(jenv);
					// change the appropriate pointer argument in the arg stack
					realOkraKernel->setPointerArg(arrayBuffer->arg_idx, arrayBuffer->addr);
					// note: must also call registerArrayMemory (until we can make this call go away)
					okraContextHolder->realContext->registerArrayMemory(arrayBuffer->addr, arrayBuffer->length * arrayBuffer->elementSize + 32);
				}
			}
		}
	}
Example #27
0
	void DX9LineRenderer::createBuffers(const Group& group)
	{
#ifdef DX9LINERENDERER_AS_LINELIST
		ArrayBuffer<LineVertex>* lvBuffer = dynamic_cast<ArrayBuffer<LineVertex>*>(group.createBuffer(GPU_BUFFER_NAME,ArrayBufferCreator<LineVertex>(2),0,false));
#else
		DX9VertexBuffer<LineVertex>* lvBuffer = dynamic_cast<DX9VertexBuffer<LineVertex>*>(group.createBuffer(GPU_BUFFER_NAME,DX9VertexBufferCreator<LineVertex>((D3DFVF_XYZ|D3DFVF_DIFFUSE), 4),0,false));
#endif
		gpuIterator = gpuBuffer = lvBuffer->getData();

#ifndef DX9LINERENDERER_AS_LINELIST
		DX9IndexBuffer<short>* ibIndexBuffer  = dynamic_cast<DX9IndexBuffer<short>*>(group.createBuffer(INDEX_BUFFER_NAME, DX9IndexBufferCreator<short>(D3DFMT_INDEX16, 6),0,false));
		indexBuffer = ibIndexBuffer->getData();

		int offsetIndex = 0;

		// initialisation de l'index buffer
		indexBuffer->Lock(0, group.getParticles().getNbReserved()*6*sizeof(short), (void**)&indexIterator, 0);

		for(size_t i = 0; i < group.getParticles().getNbReserved(); i++)
		{
//#define _DX9LINERENDERER_CLOCKWISE_
#ifdef _DX9LINERENDERER_CLOCKWISE_
			*(indexIterator++) = 0 + offsetIndex;
			*(indexIterator++) = 1 + offsetIndex;
			*(indexIterator++) = 2 + offsetIndex;
			*(indexIterator++) = 0 + offsetIndex;
			*(indexIterator++) = 2 + offsetIndex;
			*(indexIterator++) = 3 + offsetIndex;
#else
			*(indexIterator++) = 0 + offsetIndex;
			*(indexIterator++) = 2 + offsetIndex;
			*(indexIterator++) = 1 + offsetIndex;
			*(indexIterator++) = 0 + offsetIndex;
			*(indexIterator++) = 3 + offsetIndex;
			*(indexIterator++) = 2 + offsetIndex;
#endif
			offsetIndex += 4;
		}
		indexBuffer->Unlock();
		offsetIndex = 0;
#endif
	}
Example #28
0
    ArrayBuffer* readPBFile(const std::string& _fileName) {

        std::ifstream fileStream(_fileName.c_str(), std::ifstream::in);

        if(!fileStream.good()) {
            std::cerr << "could not open file " << _fileName << std::endl;
            return NULL;
        }

        int vertexCount = 0;
        fileStream >> vertexCount;

        float* data = new float[vertexCount * 10]; // all files contain 3 pos float, 3 normal floats, 3 color floats and 1 splat size!

        int pos = 0;
        while(fileStream.good() && pos < (vertexCount * 10)) {
            fileStream >> data[pos];
            pos++;
        }

        fileStream.close();

        ArrayBuffer* ab = new ArrayBuffer();
        ab->setData(vertexCount * 10 * sizeof(float), data);
        ab->defineAttribute("aPosition", GL_FLOAT, 3);
        ab->defineAttribute("aNormal", GL_FLOAT, 3);
        ab->defineAttribute("aColor", GL_FLOAT, 3);
        ab->defineAttribute("aSplatSize", GL_FLOAT, 1);

        delete[] data;

        // ab holds a copy of the data on the GPU memory
        return ab;
    }
Example #29
0
	bool DX9LineRenderer::checkBuffers(const Group& group)
	{
		ArrayBuffer<LineVertex>* lvBuffer = NULL;
		if( (lvBuffer = dynamic_cast<ArrayBuffer<LineVertex>*>(group.getBuffer(GPU_BUFFER_NAME))) == NULL )
		{
			gpuBuffer = NULL;
			return false;
		}
		gpuIterator = gpuBuffer = lvBuffer->getData();

#ifndef DX9LINERENDERER_AS_LINELIST
		DX9IndexBuffer<short>* ibIndexBuffer = NULL;
		if ((ibIndexBuffer = dynamic_cast<DX9IndexBuffer<short>*>(group.getBuffer(INDEX_BUFFER_NAME))) == NULL)
		{
			ibIndexBuffer = NULL;
			return false;
		}
		indexBuffer = ibIndexBuffer->getData();
#endif

		return true;
	}
Example #30
0
EncodedJSValue JSC_HOST_CALL structuredCloneArrayBuffer(ExecState* execState)
{
    ASSERT(execState);
    ASSERT(execState->argumentCount());
    ASSERT(execState->lexicalGlobalObject());

    ArrayBuffer* buffer = toArrayBuffer(execState->uncheckedArgument(0));
    if (!buffer) {
        setDOMException(execState, DATA_CLONE_ERR);
        return JSValue::encode(jsUndefined());
    }

    return JSValue::encode(JSArrayBuffer::create(execState->vm(), execState->lexicalGlobalObject()->arrayBufferStructure(), ArrayBuffer::tryCreate(buffer->data(), buffer->byteLength())));
}