Loading STL files with Vue-cli and Three.js
I currently have the problem that I am not able to load a STL file into a three.js scene which is created via vue-cli.
Project setup with vue-cli 'vue init webpack ProjectName', 'cd ProjectName', 'npm install three --save' and replace the 'HelloWorld' component with this code.
stl file is on the same folder as this vue component.
<template>
<div id="container"></div>
</template>
<script>
import * as THREE from 'three'
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
export default {
name: 'ThreeTest',
data() {
return {
cube: null,
renderer: null,
scene: null,
camera: null
}
},
methods: {
init: function() {
this.scene = new THREE.Scene()
this.camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
)
this.renderer = new THREE.WebGLRenderer()
this.renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(this.renderer.domElement)
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
this.cube = new THREE.Mesh(geometry, material)
var loader = new STLLoader();
loader.load( 'test.stl', function ( geometry ) {
var material = new THREE.MeshPhongMaterial( {
ambient: 0xff5533,
color: 0xff5533,
specular: 0x111111,
shininess: 200 }
);
mesh = new THREE.Mesh( geometry, material );
mesh.position.set(0, 100, 0);
this.scene.add(mesh)
}, undefined, function ( error ) {console.error( error );} );
// this.scene.add(this.cube)
this.camera.position.z = 5
const animate = function() {}
},
animate: function() {
requestAnimationFrame(this.animate)
this.cube.rotation.x += 0.01
this.cube.rotation.y += 0.01
this.renderer.render(this.scene, this.camera)
}
},
mounted() {
this.init()
this.animate()
}
}
</script>
I don't know why I have a black screen with this error:
RangeError: Invalid typed array length: 5202511335
at new Float32Array (<anonymous>)
at parseBinary (STLLoader.js?e2c6:199)
at STLLoader.parse (STLLoader.js?e2c6:396)
at Object.eval [as onLoad] (STLLoader.js?e2c6:87)
at XMLHttpRequest.eval
Can someone help me ?
Thanks! :)
Regards
See also questions close to this topic
-
How to create an order from a cart in Mongoose and delete cart
I am trying to: a) Create an order from my current cart b) Populate the response of the order with the selected object attributes in the "select" c) Finally, I would like to delete the cart.
I have tried the below but here are my problems:
- the result response does not come back populated even if the
prevProductsQuantity
constant is indeed populated - I created the function cartClear to receive the cart id and delete the document from the model but it is not working.
- I am able to create many "same" orders so I think i need to manage with a conditiona but not sure where.
The response I am looking for:
{ "success": true, "data": { "_id": "607ed5c425ae063f7469a807", "userId": "6071aed0ed7ec9344cf9616c", "productsQuantity": [ { "_id": "607f2507994d5e4bf4d91879", "productId": { "productRef": "463b8bb7-6cf6-4a97-a665-ab5730b69ba2", "productName": "table", "brand": "boehm llc", "price": 713, "__v": 0, "createdAt": "2021-04-09T18:31:43.430Z", "updatedAt": "2021-04-09T18:31:43.430Z" }, "quantity": 2, "updatedAt": "2021-04-21T15:12:51.894Z", "createdAt": "2021-04-21T15:12:51.894Z" } ], "__v": 0 }
++ THE DELETION OF THE CART ++
The current response I am getting:
{ "success": true, "data": { "state": "pending-payment", "_id": "6080507a0c758608d0dc585c", "userId": "6071aed0ed7ec9344cf9616c", "totalPrice": 1426, "productsQuantity": [ { "_id": "607f2507994d5e4bf4d91879", "productId": "60709d8f24a9615d9cff2b69", "quantity": 2, "updatedAt": "2021-04-21T15:12:51.894Z", "createdAt": "2021-04-21T15:12:51.894Z" } ], "createdAt": "2021-04-21T16:19:06.056Z", "updatedAt": "2021-04-21T16:19:06.056Z", "__v": 0 }
** AND THE CART IS NOT DELETING **
this is the code I typed for these purposes.
Any guidance is super appreciated
router.post('/', [isAuthenticated], async (req, res, next) => { try { const cart = await CartModel.findOne({ userId: req.user }).populate({ path: 'productsQuantity.productId', select: { price: 1, brand: 1, productName: 1, productRef: 1, pictures: 1 } }); const prevProductsQuantity = cart .get('productsQuantity') .map((el) => el.toObject()); const totalPriceByProduct = prevProductsQuantity.map( (product) => product.productId.price * product.quantity ); const totalPrice = totalPriceByProduct.reduce(function (a, b) { return a + b; }); const result = await OrderModel.create({ userId: req.user, totalPrice: totalPrice, state: 'pending-payment', productsQuantity: prevProductsQuantity }); const cartClear = (id) => CartModel.deleteOne({ _id: id._id }); res.status(200).json({ success: true, data: result }); cartClear(`${cart._id.toString()}`); } catch (error) { next(error); } });
- the result response does not come back populated even if the
-
How to fetch SQL data using api and use that data in react-native-svg charts? I am having an API that I want to use to fetch data and display
I am fetching some data using an api. Inside that api there are SQL queries that are executed. I have api that will be used to fetch data or execute these queries. I want to know how can I replace my chart's static data with dynamic data that will be fetched from api.
Here is my
TabDashboardDetail.js
where I am fetching title for all charts based on api data:import React from 'react'; import DefaultScrollView from '../components/default/DefaultScrollView'; import ChartView from '../components/default/ChartView'; import CogniAreaChart from '../components/CogniAreaChart'; import { areaChartData } from '../chartData'; const TabDashboardDetail = ({ navigation, route }) => { const tabsConfig = route.params.tabsConfig; return ( <DefaultScrollView> {tabsConfig.components.map((comp, index) => { return ( <ChartView key={index} title={comp.name}> <CogniAreaChart areaChartData={areaChartData} height={200} /> </ChartView> ); })} </DefaultScrollView> ); }; export default TabDashboardDetail;
Here is my
CogniAreaChart.js
which is chart file that is currently being rendered:/* eslint-disable react-native/no-inline-styles */ import React from 'react'; import { View } from 'react-native'; import { AreaChart, YAxis, XAxis } from 'react-native-svg-charts'; import * as shape from 'd3-shape'; const CogniAreaChart = ({ areaChartData, visibility, ...props }) => { const xAxis = areaChartData.message.map((item) => item[Object.keys(item)[0]]); const areaChartY1 = areaChartData.message.map( (item) => item[Object.keys(item)[1]], ); return ( <View style={{ height: props.height, flexDirection: 'row', }}> <YAxis data={areaChartY1} contentInset={{ marginBottom: 20 }} svg={{ fill: 'grey', fontSize: 12, }} /> <View style={{ flex: 1 }}> <AreaChart style={{ flex: 1 }} data={areaChartY1} contentInset={{ top: 20, bottom: 20 }} curve={shape.curveNatural} svg={{ fill: 'rgba(134, 65, 244, 0.8)' }} /> <XAxis style={{ height: 20 }} data={areaChartY1} formatLabel={(value, index) => xAxis[index]} contentInset={{ left: 30, right: 30 }} svg={{ fill: 'grey', fontSize: 12, rotation: 35, originY: 5, y: 15, }} /> </View> </View> ); }; export default CogniAreaChart;
Here is areachartData that is currently being used in
CogniAreaChart.js
:export const areaChartData = { message: [ { year: '2018', quantity: 241.01956823922, sales: 74834.12976954, }, { year: '2019', quantity: 288.57247706422, sales: 80022.3050176429, }, ], status: 'success', };
I have the API that I will replace with the example if anyone suggests.
-
Sort,Filter,search in Javascript array
Given values for acctData and balances below, write a function that returns only an array of account numbers, and accepts the following optional parameters:
- user - sortBy (accepts "acctNum" or "balance") - sortDirection (accepts "asc" or "desc"; default to asc)
Execute your function and output the results as an array in console log for the following scenarios:
a) filtered by Bob b) filtered by Charlie c) sorted by acctNum d) filtered by Alice; sorted by balance ascending
acctData = [ { "acctNum": "AAA - 1234", "user": "Alice" }, { "acctNum": "AAA - 5231", "user": "Bob" }, { "acctNum": "AAA - 9921", "user": "Alice" }, { "acctNum": "AAA - 8191", "user": "Alice" } ]; balance = { "AAA - 1234": 4593.22, "AAA - 9921": 0, "AAA - 5231": 232142.5, "AAA - 8191": 4344 };
-
WebXR: How can I adjust the eye-separation in Three.js and avoid cyclopic vision?
I can't find any info, and surprisingly all Three.js and WEBGL examples I've seen render a single camera with no separate adjustment, like setting the correct parallax is ...something optional and insignificant!
Fortunately the webxr api provides this functionality but it's not clear to me how to do this in Three.js: https://immersive-web.github.io/webxr/#xrview-interface
The only part of three.js I've found that comes close to this is WebXRManager but apparently it doesn't provide the required functionality and it needs a hack, or extension: https://github.com/mrdoob/three.js/blob/master/src/renderers/webxr/WebXRManager.js
Any hints how to do this in Three.js?
-
Using a GLTF model as the Scene in Three.js
I am new to Three.js. I am having issues using a gltf model as the actual scene and not part of the scene in three.js. The gltf model is an apartment. I want the scene to load from inside the apartment and not outside the apartment. the controls should work within the apartment too. So far, I have loaded the model on the scene but I can't get the scene to render from inside the model.
Here is my code in Typescript and also JavaScript been at it for weeks now. Any help will be much appreciated. Thank you so much.
Typescript code
import * as THREE from '/build/three.module.js' import { OrbitControls } from '/jsm/controls/OrbitControls' import { GLTFLoader } from '/jsm/loaders/GLTFLoader' import Stats from '/jsm/libs/stats.module' const scene: THREE.Scene = new THREE.Scene() const axesHelper = new THREE.AxesHelper(5) //scene.add(axesHelper) var light = new THREE.SpotLight(); light.position.set(5, 5, 5) scene.add(light); const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) camera.position.z = 2 const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer() //renderer.physicallyCorrectLights = true //renderer.shadowMap.enabled = true renderer.outputEncoding = THREE.sRGBEncoding renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) const controls = new OrbitControls(camera, renderer.domElement) const loader = new GLTFLoader() loader.load( 'apartment.glb', function (gltf) { // gltf.scene.traverse(function (child) { // if ((<THREE.Mesh>child).isMesh) { // let m = <THREE.Mesh>child // m.receiveShadow = true // m.castShadow = true // } // if ((<THREE.Light>child).isLight) { // let l = <THREE.Light>child // l.castShadow = true // //l.shadow.bias = -.003 // l.shadow.mapSize.width = 2048 // l.shadow.mapSize.height = 2048 // } // }) scene.add(gltf.scene); }, (xhr) => { console.log((xhr.loaded / xhr.total * 100) + '% loaded') }, (error) => { console.log(error); } ); window.addEventListener('resize', onWindowResize, false) function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) render() } const stats = Stats() document.body.appendChild(stats.dom) var animate = function () { requestAnimationFrame(animate) controls.update() render() stats.update() }; function render() { renderer.render(scene, camera) } animate();
JavaScript code
import * as THREE from '/build/three.module.js'; import { OrbitControls } from '/jsm/controls/OrbitControls'; import { GLTFLoader } from '/jsm/loaders/GLTFLoader'; import Stats from '/jsm/libs/stats.module'; const scene = new THREE.Scene(); const axesHelper = new THREE.AxesHelper(5); //scene.add(axesHelper) var light = new THREE.SpotLight(); light.position.set(5, 5, 5); scene.add(light); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 2; const renderer = new THREE.WebGLRenderer(); //renderer.physicallyCorrectLights = true //renderer.shadowMap.enabled = true renderer.outputEncoding = THREE.sRGBEncoding; renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls(camera, renderer.domElement); const loader = new GLTFLoader(); loader.load('apartment.glb', function (gltf) { // gltf.scene.traverse(function (child) { // if ((<THREE.Mesh>child).isMesh) { // let m = <THREE.Mesh>child // m.receiveShadow = true // m.castShadow = true // } // if ((<THREE.Light>child).isLight) { // let l = <THREE.Light>child // l.castShadow = true // //l.shadow.bias = -.003 // l.shadow.mapSize.width = 2048 // l.shadow.mapSize.height = 2048 // } // }) scene.add(gltf.scene); }, (xhr) => { console.log((xhr.loaded / xhr.total * 100) + '% loaded'); }, (error) => { console.log(error); }); window.addEventListener('resize', onWindowResize, false); function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); render(); } const stats = Stats(); document.body.appendChild(stats.dom); var animate = function () { requestAnimationFrame(animate); controls.update(); render(); stats.update(); }; function render() { renderer.render(scene, camera); } animate();
-
rendering 1 million boxes in react-three/fiber
I am testing the rendering 1 mil boxes in react-three/fiber. The performance is very slow.
function App() { const boxes = []; for (let i = 0; i < 1000; i++) { const x = Math.random(); const y = Math.random(); const z = Math.random(); const box = ( <mesh position={[x, y, z]}> <boxGeometry args={[0.01, 0.01, 0.01]} /> <meshLambertMaterial color={"red"} /> </mesh> ); boxes.push(box); } return ( <MBox style={{ height: "100vh", width: "100vw" }}> <Canvas camera={{ position: [10, 10, 10] }}> <pointLight position={[15, 15, 15]} /> {boxes} <OrbitControls /> <Stats /> </Canvas> </MBox> ); }
The render is responsive with 1000 boxes (60 FPS). With 10000 boxes, it drops to 7 FPS with a bit lack. The browser dies with 100000 boxes.
The computer dedicated GPU NVIDIA is not utilized at all.
Any idea to improve the performance please?
-
Should the deallocate function be called when an error occurs in the STL allocator allocate?
try { node = allocator.allocate(LIST_BASIC_UNIT); } catch (...) { allocator.deallocate(node); throw; }
Should I call deallocator when an exception occurs in the STL allocator allocate?
-
Is the std::function object itself thread safe? If no, what ways can I make it thread safe?
I have an
std::function
object that many threads access. Threads can can change the function it points to (through its copy constructor) and can call the function it points to.So, my question is, that in what ways is the
std::function
object itself thread safe? I'm not talking about the function it points to/calls, I'm talking about the std::function object itself.There are surprisingly only a few sites on the internet that talk about this, and all of them (what I encountered) talk about the function it points to, not the object itself.
These are the main sites I've read:
Does std::function lock a mutex when calling an internal mutable lambda?
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4348.html
If you read them, you can see that none of them talk about the safety of the std::function object itself.
According to the second answer on this page, the STL library is thread safe in these cases:
simultaneous reads of the same object are OK
simultaneous read/writes of different objects are OK
Based on this, when I'm setting the function the
std::function
object points to, for this use case thestd::function
object is not thread safe. But I'm asking just in case it is, because according to this question's answer, it has some kind of internal mutex.So, what way can I make it thread safe? One option would be using mutexes, but that won't fully work due to the example demonstrated below:
Suppose I have an
std::function
objectfunc
andstd::mutex m
to protect func. I lock m and call the function (to protect other threads from setting func while the function it points to is being called) and will unlock m when the function exits. Lets say this function call will take very long. This way, when one thread wants to set func, it will attempt to lock the mutex, but will be blocking until the latter function call exits. What can I do in this case?I thought of using a pointer that will point to an std::function object. This way, I will use the mutex to protect this pointer and when I will make a function call, I lock the mutex just for getting retrieving the function object from the pointer.
-
Can insert into vector Out of order?
I want to insert
vec1
byvec2
andvec3
. When I insertvec3
first, the program cannot exit successfully. But when I insertvec2
and then insertvec3
, the program can exit successfully. I want to know the failed reason.Why insert
vec1
Out of order: I want to insert it by two different threads( The two threads will write to different positions and do not affect each other.), so the order cannot be guaranteed.#include <iostream> #include <vector> #include <chrono> using namespace std::chrono; using namespace std; struct DocIdAndPayLoad { uint64_t m_docId; DocIdAndPayLoad() { DefaultCnt++; } DocIdAndPayLoad(const DocIdAndPayLoad& /*_bond_rhs*/) { CopyCnt++; } DocIdAndPayLoad(DocIdAndPayLoad&& _bond_rhs) { MoveCnt++; } DocIdAndPayLoad& operator=(const DocIdAndPayLoad& _bond_rhs) { AssignCnt++; return *this; } static int DefaultCnt; static int CopyCnt; static int MoveCnt; static int AssignCnt; }; int DocIdAndPayLoad::DefaultCnt = 0; int DocIdAndPayLoad::CopyCnt = 0; int DocIdAndPayLoad::MoveCnt = 0; int DocIdAndPayLoad::AssignCnt = 0; int main() { const int hugeSize=10000; vector<DocIdAndPayLoad> vec1; cout<<vec1.size()<<" "<<vec1.capacity()<<endl; vector<DocIdAndPayLoad> vec2(hugeSize/2); vector<DocIdAndPayLoad> vec3(hugeSize/2); auto start1 = high_resolution_clock::now(); vec1.reserve(hugeSize); //vec1.insert(vec1.begin()+hugeSize/2, std::make_move_iterator(vec3.begin()), std::make_move_iterator(vec3.end())); vec1.insert(vec1.begin(), std::make_move_iterator(vec2.begin()), std::make_move_iterator(vec2.end())); auto stop1 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop1 - start1); cout << "Cost1: "<< duration.count() << " microseconds" << endl; vector<DocIdAndPayLoad> vec4; auto start2 = high_resolution_clock::now(); vec4.resize(hugeSize); auto stop2 = high_resolution_clock::now(); auto duration2 = duration_cast<microseconds>(stop2 - start2); cout << "Cost2: "<< duration2.count() << " microseconds" << endl; cout<<vec1.size()<<" "<<vec1.capacity()<<endl; return 0; }
-
Vue 3 & Composition API : template refs in v-for loop error : only get proxies
I've been developing my first project with Vue3.js & Vue Cli and I've been stuck for the past couple of hours on this bit of code.
Basically what I'm trying to do is to have a list of buttons based on an array of objects created in the setup() part of the code. All objects also contain their own ref within the array itself, which I eventually bind on the template. I then make consts out of each ref so that I can use them within the setup() but when I console.log(btnConvert.value) I get a proxy, which I don't with my other refs that aren't within a v-for loop.
RefImpl {_rawValue: Proxy, _shallow: false, __v_isRef: true, _value: Proxy}
Here's the expanded version of the console.log(btnConvert.value)
Proxy {…} [[Handler]]: Object get: ƒ get({ _: instance }, key) has: ƒ has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) ownKeys: (target) => {…} set: ƒ set({ _: instance }, key, value) [[Prototype]]: Object [[Target]]: Object [[IsRevoked]]: false
I tried everything I could think of, but I couldn't understand the official Vue doc. Could anyone help me understand how I could retrieve the DOM elements with those refs? Thank you very much !
Here's the bit of relevant code (I removed the functions to which the btn refer for ease of lecture).I can add some more if necessary.
<template> <div> <div ref="btnList" class="options"> <vBtn v-for="btn in btnArray.slice(1)" :key="btn" :ref="btn.ref" class="btn" :class="`btn--${btn.class}`" @click="btn.action" v-html="btn.text" /> </div> </template>
<script> import { ref, onMounted } from 'vue' import vBtn from '@/components/Tool/vBtn.vue' export default { components : { vBtn }, setup() { const btnConvert = ref(null) const btnCopy = ref(null) const btnCancel = ref(null) const btnUndo = ref(null) const btnErase = ref(null) const btnArray = [ { class: 'convert', text: 'some text', action: convertText, ref: btnConvert }, { class: 'undo', text: 'some text', action: undoConvert, ref: btnUndo }, { class: 'cancel', text: 'some text', action: cancelChange, ref: btnCancel }, { class: 'erase', text: 'some text', action: eraseText, ref: btnErase }, { class: 'copy', text: 'some text', action: copyText, ref: btnCopy } ] onMounted() { console.log(btnConvert.value) // this is where I get the proxy } }, } </script>
-
Getting js and css url generated during vuecli serve
Am trying to use vuecli in a php project and i would like to get the url of the js and css file during serve for hot reload
In my package.json i have added the following scripts
"scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build" },
I have also added the following in vue.config.js
"use strict"; const WebpackAssetsManifest = require("webpack-assets-manifest"); const host = "0.0.0.0"; const port = 8081; const path = require("path"); module.exports = { outputDir:"web-assets", productionSourceMap:false, // delete HTML related webpack plugin configureWebpack:function(config){ let obj = { plugins : [ new WebpackAssetsManifest(), ] }; if (process.env.NODE_ENV === "production") { obj.optimization = { splitChunks: { chunks: "all", minSize: 200000, maxSize: 244000, } }; } return obj; }, publicPath: `http://${host}:${port}/`, devServer: { port, host, hotOnly: true, disableHostCheck: true, clientLogLevel: "warning", inline: true, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" }, watchOptions: { poll: true } }, chainWebpack: config => { config.plugins .delete("html") .delete("preload") .delete("prefetch"); config .entry("app") .clear() .add("./vue-app/main.js") .end(); config.resolve.alias .set("@", path.join(__dirname, "./vue-app")) }, };
The above works well on
npm run build
where after running it creates amix-manifest.json
where i can easily use the paths but during serve it doesnt create a mix-manifest.jsonHow can i get the path of asset(js and css) file generated during
npm run serve
to use in my php file. -
Use external stylesheet for Vue web component / Prevent inlining styles
I am using an
vue-cli-service
to build a web component. All styles referenced in this component are always inlined into the javascript file.vue-cli-service build --target wc --name component-name --inline-vue ./src/components/someComponent.vue
Is there a way to force Vue to pull out component CSS into a separate file instead of inlining it into the
dist/component-name.js
file?Alternatively, is there an easy way to allow external users to override the Shadow DOM styles?