React - Three.js - GLTFLoader "JSON.parse error" - reactjs

so whenever I want to import a model via GLTFLoader locally I get this error:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
but when I try it via a link it works.
The link I tried with is:
https://s3-us-west-2.amazonaws.com/s.cdpn.io/39255/ladybug.gltf
I tested the models I used in the official three.js-Editor and even exported them from there to get a "clean" gltf model. I also saved the content of the link in a gltf file and it didnt work neither.
This is my code:
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
async function run() {
try {
var loader = new GLTFLoader();
loader.crossOrigin = true;
loader.load(
"./scene.gltf",
//"https://s3-us-west-2.amazonaws.com/s.cdpn.io/39255/ladybug.gltf",
function (data) {
var object = data.scene;
object.position.set(0, 0, 0);
scene.add(object);
}
);
} catch (e) {
console.log(e);
}
}
run();

As Marquizzo said: You have to run a local server for the models. You cannot import them via a path normally, because of security restrictions.

Related

Error: Zxing functions does not exists. React QR Scanning App

I am trying add a qr code scanning functionality to my react app. I am using #zxing(https://www.npmjs.com/package/#zxing/browser & https://www.npmjs.com/package/#zxing/library) packages.
Following the readme, here's my js code. I have hosted the application on aws so its SSL covered. But I can't seem to figure out the issue. I have read the git repo of both and the functions do exists(https://github.com/zxing-js/browser/tree/master/src/readers)
import React, { useState, useEffect } from "react";
import {
NotFoundException,
ChecksumException,
FormatException
} from "#zxing/library";
import { BrowserQRCodeReader, BrowserCodeReader } from '#zxing/browser';
export default function() {
var qrCodeReader = null;
var codeReader = null;
var sourceSelect = null;
console.log("ZXing code reader initialized");
useEffect(() => {
codeReader = new BrowserCodeReader();
qrCodeReader = new BrowserQRCodeReader();
console.log(codeReader.listVideoInputDevices()); // ISSUE: RETURNS -> listVideoInputDevices() is not a fuction
console.log(qrCodeReader.listVideoInputDevices()); // ISSUE: RETURNS -> listVideoInputDevices() is not a fuction
console.log("Code Reader", codeReader); // ISSUE: SEE IMAGE BELOW
console.log("QR Code Reader", qrCodeReader); // ISSUE: SEE IMAGE BELOW
}, []);
Instead of using the import try using:
`
const zxing = require('zxing-js/library');
`

importing 3d models into babylon when using react

I have been using babylonjs within a reactjs environment and so far it's very good. However i've been having trouble loading 3d models into the canvas. I've managed to load models into a non-react environment but not the react environment.
You can see a simple example of my current code below.
import React from 'react'
import {useEffect, useState, useRef} from 'react'
import path from 'path'
import * as BABYLON from '#babylonjs/core'
import 'babylonjs-loaders'
import SceneComponent from 'babylonjs-hook'; // ^^ point to file we created above or 'babylonjs-hook' NPM.
import SceneComp from '../components/babylonComponent'
const MyPage = () =>{
var box = undefined
var page = "landing"
//this configures the scene
const onSceneReady = (scene) =>{
scene.clearColor = BABYLON.Color3.Black()
//create and position free camera
var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 5, -10), scene)
//this targets the camera to scene of origin
const canvas = scene.getEngine().getRenderingCanvas()
//attatch camera to canvas
camera.attachControl(canvas, true)
//this creates a light aiming 0,1,0 - to the sky (non - mesh)
var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0,1,0), scene)
//default intensity is 1, let's dim the light a small amount
light.intensity = 0.7
var myModel = BABYLON.SceneLoader.Append("./3dAssetts/untitled-scene-babylon/", "untitled-scene.babylon", scene, function(meshes){
})
return scene
}
//this funciton will run on every frame render
const onRender = (scene) =>{
}
return(
<div>
<div style={canvasStyler}>
<SceneComp antialias onSceneReady={onSceneReady} onRender={onRender} id='my-canvas' />
</div>
</div>
)
}
const menuButton= {
color:'black',
textDecoration:'none',
}
const canvasStyler ={
position:'absolute',
width:'100%',
top:'0px',
zIndex:'-1'
}
export default MyPage
The canvas and the page loads fine but the 3d model does not and I am getting the following error.
Unable to load from ./3dAssetts/untitled-scene-babylon/untitled-scene.babylon: importScene of undefined from undefined version: undefined, exporter version: undefinedimportScene has failed JSON parse
Unable to work out what i'm doing wrong, anybody got any ideas?
I have managed to get .babylon 3d model files imported using the following
I created an assets folder within the create-react-app /public folder.
I then put my .babylon file within this folder and called it in the import mesh code using the following.
var car = BABYLON.SceneLoader.Append("./assets/", "carModel.babylon", scene, function(meshes){
})
However i'm still having problems loading other object file types such as .gltf and .OBJ
for further info see the following useful link
https://www.html5gamedevs.com/topic/40304-trouble-loading-assets-in-react/
If you are using version 4, try replacing
import 'babylonjs-loaders'
with
import '#babylonjs/loaders'

angular 9.1 and babylon 4.1 loading gltf issue

Day 1 on babylon.js. I have cloned this repository for angular 9.1 and babylon 4.1 starter kit. I am able to run the project.
Next step is that I wanted to load the gltf model for which I have installed the package babylonjs-loaders and used the library but getting error that path to model 404.
Code:
import { WindowRefService } from './../services/window-ref.service';
import {ElementRef, Injectable, NgZone} from '#angular/core';
import {
Engine,
FreeCamera,
Scene,
Light,
Mesh,
Color3,
Color4,
Vector3,
HemisphericLight,
StandardMaterial,
Texture,
DynamicTexture
} from 'babylonjs';
import 'babylonjs-materials';
import 'babylonjs-loaders';
#Injectable({ providedIn: 'root' })
export class EngineService {
private canvas: HTMLCanvasElement;
private engine: BABYLON.Engine;
private camera: BABYLON.FreeCamera;
private scene: BABYLON.Scene;
private light: BABYLON.Light;
private sphere: Mesh;
public constructor(
private ngZone: NgZone,
private windowRef: WindowRefService
) {}
public animate(): void {
// We have to run this outside angular zones,
// because it could trigger heavy changeDetection cycles.
this.ngZone.runOutsideAngular(() => {
const rendererLoopCallback = () => {
this.scene.render();
};
if (this.windowRef.document.readyState !== 'loading') {
this.engine.runRenderLoop(rendererLoopCallback);
} else {
this.windowRef.window.addEventListener('DOMContentLoaded', () => {
this.engine.runRenderLoop(rendererLoopCallback);
});
}
this.windowRef.window.addEventListener('resize', () => {
this.engine.resize();
});
});
}
public loadScene(canvas: ElementRef<HTMLCanvasElement>): void {
// The first step is to get the reference of the canvas element from our HTML document
this.canvas = canvas.nativeElement;
// Then, load the Babylon 3D engine:
this.engine = new BABYLON.Engine(this.canvas, true);
// create a basic BJS Scene object
this.scene = new BABYLON.Scene(this.engine);
this.scene.clearColor = new Color4(0, 0, 0, 0);
// create a FreeCamera, and set its position to (x:5, y:10, z:-20 )
this.camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(5, 10, -20), this.scene);
// target the camera to scene origin
this.camera.setTarget(BABYLON.Vector3.Zero());
// attach the camera to the canvas
this.camera.attachControl(this.canvas, false);
// create a basic light, aiming 0,1,0 - meaning, to the sky
this.light = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0, 1, 0), this.scene);
BABYLON.SceneLoader.Append("./", "bmw.gltf", this.scene, function (scene) {
// do something with the scene
});
}
}
I have googled on similar question but did not reach to any conclusion. I might be missing something basic. I have kept the gltf on the same directory as ts file and path is proper. I have tested with putting png image on same path and able to see it in network tab of chrome dev tool with 200 status.
Please help guys. I am guessing the way i am importing babylonjs-loaders is the culprit here.
error screenshot:
Your bmw.gltf file should be located in your assets folder.
this means that you will have to load the files from there.
BABYLON.SceneLoader.Append("/assets", "bmw.gltf"

SharePoint SPFX: Unable to get property 'Context'

I'm working on a custom SPFX commandset. It opens a dialog with an iframe to an 3rth party platform. I'm able to receive a json through a postmessage. From this json, I convert it's data to a file, with it's proper metadata. All of this works like a charm... Except...
Now I want to upload this file to a document library, and it drives me crazy.
I'm referencing:
import "#pnp/polyfill-ie11";
import { ConsoleListener, Logger, LogLevel } from "#pnp/logging";
import { sp } from "#pnp/sp";
import { Web } from "#pnp/sp/webs";
import "#pnp/sp/webs";
import "#pnp/sp/files";
import "#pnp/sp/folders";
import { Base64 } from 'js-base64';
In my dialog component, I try to upload the file with web.getFolderByServerRelativeUrl. But this method is failing, and I really don't understand why.... Looking at the pnp reference (https://pnp.github.io/pnpjs/sp/files/), It seems like the right way.
var file = Base64.atob(response.Data);
console.log("File length : " + file.length);
let web = Web("https://MyTenant.sharepoint.com/sites/Customer"); // this is successful
await web.getFolderByServerRelativeUrl("/sites/Customer/Shared%20Documents/")
.files.add(response.fileName, file, true); // this fails
The context is set on the CommandSet onInit()
#override
public onInit(): Promise<void> {
Log.info(LOG_SOURCE, 'Initialized myCommandSet');
pnpSetup({
spfxContext: this.context
});
return Promise.resolve();
}
Hope you guys and girls can point me in the right direction...
EDIT:
Error:
HTTP400: INVALID REQUEST - The request could not be processed by the server
due to an invalid syntax
POST - https://MyDevTenant.sharepoint.com/sites/customer/
_api/web/getFolderByServerRelativeUrl
('%2Fsites%2Customer%2FShared%2520Documents%2F')
/files/add(overwrite=true,url='')
Is it the url from the documentlibrary that messes things up?
Thanks to Willman for giving me a right direction.
This did the trick:
import { sp, Web, IWeb } from "#pnp/sp/presets/all";
import "#pnp/sp/webs";
import "#pnp/sp/lists";
import "#pnp/sp/files";
import "#pnp/sp/folders";
const web = await sp.web();
const list = sp.web.getList("Documents");
const listId = await list.select("Id")();
await sp.web.lists.getById(listId.Id).rootFolder.files.add(docname, file, true);

Sonarqube : Create a custom page using react

I would like to create a custom page using react but I cannot find the documentation to do this. On the Sonarqube documentation, there only the way to create a custom page using javascript only and I don’t understand how the example plugin works with react.
Can you tell me if there is a documentation that I can use.
Short answer: There isn't. There is barely anyone (no one in fact, as far as I've seen) using custom pages currently.
However, it IS possible. You need to create a react project with Webpack (or a similar JS packager).
I also recommend using Create-React-App. This fixes a lot of the setup for you. After that, in your index.js you use the example code from the SonarQube wiki.
Here is an example:
/*
PRODUCTION ENTRYPOINT
*/
import React from 'react';
import ReactDOM from 'react-dom';
import Project from './components/Project';
import './main.css';
window.registerExtension('myplugin/coverage', function (options) {
appendCustomCSS();
let isDisplayed = true;
window.SonarRequest.getJSON('/api/measures/component', {
component: options.component.key,
metricKeys: 'coverage'
}).then(function (response) {
if (isDisplayed) {
let obj = JSON.parse(response.component.measures[0].value);
let div = document.createElement('div');
render(obj, div);
options.el.appendChild(div);
}
});
return function () {
isDisplayed = false;
};
});
function appendCustomCSS() {
let fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", "/static/myplugin/coverage.css");
document.head.append(fileref);
}
function render(objectArray, container) {
ReactDOM.render(<div className="Coverage"><Project objects={objectArray}/></div>, container);
}

Resources