Guide for applying 2D texture labels onto a 3D object

I am working with a texture file applied to a complex 3D object in the format of an .OBJ file. This texture contains various labels, and I would like to generate additional objects for these distinctive labels at their corresponding locations on the 3D model, allowing for interactive functionality.

While researching a solution, I came across a thread that utilizes outdated methods such as Geometry: Three.js - calculate 3D coordinates from UV coordinates

I am unsure how to adapt this approach to the latest version of ThreeJS, or if there is a more effective method to accomplish my objective.

For context regarding the specific 3D object, it pertains to human muscle anatomy, with the texture serving as both labels and color shading for the muscles.

As a newcomer to ThreeJS and 3D modeling, I acknowledge that I may be missing some crucial details.

Answer №1

It is unlikely that you can directly make points on your texture interactive, but have you explored the option of using CSS2DRenderer?

Check out some examples below:
css2d_label
molecules

To implement this, I suggest creating a button or label element for each point within the DOM, or reference an existing element with getElementById. Then, create a new CSS2DObject for each label/button, specify their positions in relation to your 3D object, and add them to your scene.

const labelOne = document.getElementById('labelOne');
const labelTwo = document.getElementById('labelTwo');

const labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(labelRenderer.domElement);

const labelObjOne = new CSS2DObject(labelOne.nativeElement);
labelObjOne.position.set(0, 0, 0);
scene.add(labelObjOne);

const labelObjTwo = new CSS2DObject(labelTwo.nativeElement);
labelObjTwo.position.set(0, 1, 0);
scene.add(labelObjTwo);

This method may require you to remove any existing labels from your texture for a cleaner look.

Answer №2

After conducting extensive research, I finally discovered the solution I had been seeking.

To view my code, which unfortunately is too lengthy to display here, please visit https://github.com/tedik123/Obj-Extraction

The crucial first step was realizing that in my case with the .obj file, everything was stored in parallel UVs, vertices (faces), and normals (applicable to any ThreeJS object). The challenge lay in the fact that the UVs and faces were organized as 1-dimensional arrays. Additional effort was required to structure them into triplets for indexing by face index, where each index retrieves all the vertices, UVs, and normals comprising one face - each face consisting of 3 vertices, 3 normals, and 3 UVs. Preprocessing in a manner where a face index yielded all relevant data streamlined most of the process. For further understanding, refer to this informative link:

Subsequently, I transitioned to Python for its user-friendliness in addressing a one-time task: extracting all pixels constituting a single label on the texture. Since each label bore a distinct color in my case, identifying and saving them via dictionary mapping proved efficient - associating the label as the key and the pixel composition as the value.

The third pivotal realization was that UVs form triangles! Each face represents a triangle, featuring a corresponding textured triangle. Fortunately, UVs are confined to 2D space while faces inhabit 3D space, simplifying spatial alignment given our preprocessed UVs, faces, and normals indexed by face. This arrangement obviates the need for manual mapping.

Further steps involved dissecting the UV triangles* by converting them to integer-based pixel coordinates and identifying points within each triangle's perimeter, subsequently storing these in a hash map corresponding to their respective face indices. Although time-consuming initially, this optimization significantly accelerates subsequent searches. Running this process once allows for future expedited executions, especially if saved to a file.

I utilized the following code references to aid me in deciphering triangles: Determining all discrete points inside a triangle and Get all points of a straight line in python

By cross-referencing our label pixels against the aforementioned dictionary to determine their corresponding faces, we can then import this information back into JavaScript. Creating a new Buffer Geometry object entails adding the vertices composing the desired label face(s) before generating the mesh (ensuring color setting for visibility) along with adjustments for position and scale relative to the original object. This process yields a 3D object overlaying the designated label area.

*Alternatively, one could iterate through each pixel label to ascertain its presence within a UVs triangle, albeit at O(n^2) complexity - potentially impractical for large textures or complex objects with numerous vertices. While more precise, such an approach sacrifices speed efficiency compared to my method operating at O(n) with marginal accuracy trade-offs.

In upcoming revisions, I intend to append concise functioning code snippets to this response; although presently, substantial cleanup remains imperative!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubles with Angular2 template parser when parsing HTML fragment that is W3C validated

The online W3C validator successfully parses the following document: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>test</title> </head&g ...

WebStorm is not auto-completing the Emotion Styled Components

While using @emotion/styled in WebStorm, I have noticed that there is no Intellisense for autocomplete within my style object. However, Typescript does seem to be checking to some extent: const StepTimer = styled.button({ borderRadius: 50, height: &ap ...

What is the best method for showcasing this console.log information in an Angular application?

I have developed a feature that displays users who are online. While it works perfectly in the console log, I am struggling to show p as the result if the user is online. Below is the code snippet: ngOnInit() { this.socket.emit('online', { r ...

What happens when i18next's fallbackLng takes precedence over changeLanguage?

I am currently developing a Node.js app with support for multi-language functionality based on the URL query string. I have implemented the i18next module in my project. Below is a snippet from my main index.ts file: ... import i18next from 'i18next& ...

The JSON input abruptly reached its end during parsing at an unexpected moment

When attempting to write to an existing JSON file, I discovered that I need to read the file, insert the new item, and then write it again. This process usually works fine, but occasionally I encounter an error message that reads, "Unexpected end of JSON ...

Error in Vue-TypeScript application: Attempting to access properties of an undefined variable (specifically 'config')

Just starting out with Vue 3 & TypeScript and diving into PrimeVue. Currently, I'm working on a simple todo app to get the hang of things. However, I've hit a roadblock with an error message that reads: Uncaught TypeError: Cannot read properties ...

Retrieving the row value of a checkbox in an Angular table

I'm facing a challenge where I have a table with three columns, one of which is a checkbox. Here is an image for reference: https://i.sstatic.net/4U6vP.png Here is the code snippet: <div nz-row> <nz-table nz-col nzSpan="22" [nzLoading] ...

Encountering difficulties when installing dependencies in a React project

Encountering an issue while trying to add a new dependency to my React project. The error message I receive is as follows: C:\Users\abhinavverma Desktop Sodexo-Fe Matchiq-fe> npm i @cypress/instrument-cra npm ERR! code ERESOLVE npm ERR! ERES ...

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...

The index type 'X' is not allowed for use in this scenario

I encountered an issue in my TypeScript code: error message: 'Type 'TransitionStyles' cannot be used as an index type.' I'm wondering if there's a way to modify my interface so that it can be used as an index type as well: ...

Exploring Three.js: Meshing in Both 2D and 3D

Can Canvas2D be utilized for rendering graphics in the scene? Specifically, can shapes and/or meshes be drawn independently of the camera's position, rotation, and zoom? Our application requires some drawing functionality (not related to GUI elements, ...

The implementation of getStaticPaths was done independently of getStaticProps - TypeScript

I am currently in the process of setting up a new blog using a combination of nextJS, TypeScript, and sanity CMS. The homepage is already set up to display posts perfectly. Next on my list is to display the details of each post when it is clicked, based on ...

Getting the result from a callback function in TypeScript

In my Typescript file Service.ts, I have a function called doCallAuth: export const doCallAuth = (username, password) => { var auth = new Auth({ url: '...', }); var status; auth.authenticate(username, password ...

What is the best way to update the value of a variable within a specific child component that is displayed using ngFor?

Hello there, I'm in need of some assistance with a coding issue. I have a parent component named "users-list" that displays a list of child components called "user" using *ngFor. Each component's class is dynamic and depends on various internal v ...

Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How ...

Transforming an array into a string using Map Reduce

I am using an array map function to simplify an array of objects into a single string. const formatEmails: (arr: { "default" : string }[]) => string = (arr: { "default" : string }[]) => arr.map(e => e["default"]).reduce((e, i) => e + i + "; " ...

Are auto-properties supported in TypeScript yet?

I've heard that properties in Typescript can be defined like they are in C# with automatic setters and getters. However, I have found it difficult to implement properties this way as the intellisense does not support such syntax in Typescript. I tried ...

When a Vue3/Vuex object created using reactive() is used as a payload in a mutation to Vuex, it loses its reactivity

Ever wondered why you might need a reactive object compatible with Provide/Inject for your Vuex Store? Well, it's all about flexibility and functionality! Picture this: you have a plugin for authentication that needs to be integrated into your app. B ...