Skip to content

Commit

Permalink
get all bubbles upon login
Browse files Browse the repository at this point in the history
  • Loading branch information
Eric Wang committed Nov 5, 2023
1 parent e449ed8 commit 7ad199a
Show file tree
Hide file tree
Showing 5 changed files with 126 additions and 70 deletions.
116 changes: 84 additions & 32 deletions app/newHere1/newHere/CustomARViewRepresentable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import ARKit

struct CustomARViewRepresentable: UIViewRepresentable {
@EnvironmentObject var messageState: MessageState
@EnvironmentObject var fetchedMessagesState: FetchedMessagesState

func makeUIView(context: Context) -> ARSCNView {
// return CustomARView()
Expand All @@ -27,6 +28,33 @@ struct CustomARViewRepresentable: UIViewRepresentable {
let configuration = ARWorldTrackingConfiguration()
sceneView.session.run(configuration)

getUserMessages(userId: "653d51478ff5b3c9ace45c26") {
result in
switch result {
case .success(let response):
print("Messages fetched successfully: \(response)")
var convertedMessages:[Message] = []
for m in response {
do {
let convertedMessage = try Message(id: m._id,
location: m.location.toCLLocation(),
messageStr: m.text)
convertedMessages.append(convertedMessage)
}
catch {
// Handle the error
print("Error: \(error)")
}
}

fetchedMessagesState.fetchedMessages = convertedMessages
renderBubbleNodeHistory(to: sceneView, messages: convertedMessages)

case .failure(let error):
print("Error getting messages: \(error.localizedDescription)")
}
}

return sceneView
}

Expand All @@ -51,10 +79,6 @@ struct CustomARViewRepresentable: UIViewRepresentable {
}

func plantBubbleNode(to sceneView: ARSCNView, message: Message) {
let bubble = SCNSphere(radius: 0.05)
bubble.firstMaterial?.diffuse.contents = UIColor(red: 135.0/255.0, green: 206.0/255.0, blue: 235.0/255.0, alpha: 1.0)

let bubbleNode = SCNNode(geometry: bubble)
// Set the position based on the provided position
if let frame = sceneView.session.currentFrame {
let transform = frame.camera.transform
Expand All @@ -63,44 +87,72 @@ struct CustomARViewRepresentable: UIViewRepresentable {
let forwardDirection = SCNVector3(-transform.columns.2.x, -transform.columns.2.y, -transform.columns.2.z)

// Calculate the position 2 meters in front of the camera
let position = SCNVector3(
let shifted_position = SCNVector3(
transform.columns.3.x + forwardDirection.x * 0.5,
transform.columns.3.y + forwardDirection.y * 0.5,
transform.columns.3.z + forwardDirection.z * 0.5
)

// Create an SCNText geometry for the first text
let textGeometry1 = SCNText(string: message.author, extrusionDepth: 0.001)
textGeometry1.firstMaterial?.diffuse.contents = UIColor.black
let textNode1 = SCNNode(geometry: textGeometry1)


// TEXT POSITIONING RELATIVE TO BUBBLE - WILL HAVE TO ADJUST LATER

// Position the first textNode inside the bubble
textNode1.position = SCNVector3(-0.05, 0, -0.05) // Adjust the position inside the bubble
textNode1.scale = SCNVector3(0.001, 0.001, 0.001)

// Create an SCNText geometry for the second text
let textGeometry2 = SCNText(string: message.messageStr, extrusionDepth: 0.001)
textGeometry2.firstMaterial?.diffuse.contents = UIColor.black
let textNode2 = SCNNode(geometry: textGeometry2)
newBubbleNode(to: sceneView, message: message, position: shifted_position)
}
}

func renderBubbleNodeHistory(to sceneView: ARSCNView, messages: [Message]) {
// Create a random number generator
var randomNumberGenerator = SystemRandomNumberGenerator()

// Position the second textNode inside the bubble, stacked on top of the first
textNode2.position = SCNVector3(-0.05, 0, 0.05) // Adjust the vertical position inside the bubble
textNode2.scale = SCNVector3(0.001, 0.001, 0.001)
// Define the range of random positions for x, y, and z coordinates
let xRange: ClosedRange<Float> = -3.0...3.0 // Represents a 10-meter width (-5m to +5m)
let yRange: ClosedRange<Float> = 0.0...3.0 // Represents a height range above the ground (0m to +2m)
let zRange: ClosedRange<Float> = -3.0...3.0 // Represents a 10-meter depth (-5m to +5m)

// Add both text nodes as children of the bubbleNode
bubbleNode.addChildNode(textNode1)
bubbleNode.addChildNode(textNode2)
for message in messages {
// Generate random positions
let randomX = Float.random(in: xRange, using: &randomNumberGenerator)
let randomY = Float.random(in: yRange, using: &randomNumberGenerator)
let randomZ = Float.random(in: zRange, using: &randomNumberGenerator)

print("\(message.author), \(message.messageStr)")
// Set the node's position to the calculated position 2 meters in front of the camera
bubbleNode.position = position
// Create an SCNVector3 using the random positions
let randomPosition = SCNVector3(randomX, randomY, randomZ)

newBubbleNode(to: sceneView, message: message, position: randomPosition)
}

}

func newBubbleNode(to sceneView: ARSCNView, message:Message, position:SCNVector3) {
let bubble = SCNSphere(radius: 0.05)
bubble.firstMaterial?.diffuse.contents = UIColor(red: 135.0/255.0, green: 206.0/255.0, blue: 235.0/255.0, alpha: 1.0)

let bubbleNode = SCNNode(geometry: bubble)

// Create an SCNText geometry for the first text
let textGeometry1 = SCNText(string: message.id, extrusionDepth: 0.001)
textGeometry1.firstMaterial?.diffuse.contents = UIColor.black
let textNode1 = SCNNode(geometry: textGeometry1)


// TEXT POSITIONING RELATIVE TO BUBBLE - WILL HAVE TO ADJUST LATER

// Position the first textNode inside the bubble
textNode1.position = SCNVector3(-0.05, 0, -0.05) // Adjust the position inside the bubble
textNode1.scale = SCNVector3(0.001, 0.001, 0.001)

// Create an SCNText geometry for the second text
let textGeometry2 = SCNText(string: message.messageStr, extrusionDepth: 0.001)
textGeometry2.firstMaterial?.diffuse.contents = UIColor.black
let textNode2 = SCNNode(geometry: textGeometry2)

// Position the second textNode inside the bubble, stacked on top of the first
textNode2.position = SCNVector3(-0.05, 0, 0.05) // Adjust the vertical position inside the bubble
textNode2.scale = SCNVector3(0.001, 0.001, 0.001)

// Add both text nodes as children of the bubbleNode
bubbleNode.addChildNode(textNode1)
bubbleNode.addChildNode(textNode2)

print("\(message.id), \(message.messageStr)")
// Set the node's position to the calculated position 2 meters in front of the camera
bubbleNode.position = position
sceneView.scene.rootNode.addChildNode(bubbleNode)
}

}
52 changes: 28 additions & 24 deletions app/newHere1/newHere/Home.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,44 +12,48 @@ class MessageState: ObservableObject {
@Published var currentMessage: Message?
}

class FetchedMessagesState: ObservableObject {
var fetchedMessages: [Message]?
}

struct HomePageView: View {
@State private var isShowingProfile = false
@State private var isShowingMessages = false
@State private var isShowingPosts = false
@State private var storedMessages: [Message] = []


@EnvironmentObject var locationDataManager: LocationDataManager

@StateObject var messageState = MessageState()
@StateObject var fetchedMessagesState = FetchedMessagesState()

var body: some View {
CustomARViewRepresentable()
.environmentObject(messageState)
.environmentObject(fetchedMessagesState)
.ignoresSafeArea()
.overlay(alignment: .bottom){
VStack(){
if let currentLocation = locationDataManager.location {
Text("Your current location is:")
Text("Latitude: \(currentLocation.coordinate.latitude.description)")
Text("Longitude: \(currentLocation.coordinate.longitude.description)\n")
} else {
Text("Finding your location...\n")
ProgressView()
}
// if let currentLocation = locationDataManager.location {
// Text("Your current location is:")
// Text("Latitude: \(currentLocation.coordinate.latitude.description)")
// Text("Longitude: \(currentLocation.coordinate.longitude.description)\n")
// } else {
// Text("Finding your location...\n")
// ProgressView()
// }

// render the stored messages on the screen
if !storedMessages.isEmpty {
List {
ForEach(0..<storedMessages.count, id:\.self) { i in
Text(storedMessages[i].displayMessage())
}
}
.listStyle(PlainListStyle())
.background(Color.clear) // Set the list background to clear
}
else {
Text("No Messages Stored!")
// // render the stored messages on the screen
// if !storedMessages.isEmpty {
// List {
// ForEach(0..<storedMessages.count, id:\.self) { i in
// Text(storedMessages[i].displayMessage())
// }
// }
// .listStyle(PlainListStyle())
// .background(Color.clear) // Set the list background to clear
// }
// else {
// Text("No Messages Stored!")
}

Spacer()
Expand Down Expand Up @@ -103,15 +107,15 @@ struct HomePageView: View {
MessagesPopup(isPresented: $isShowingMessages)
}
.sheet(isPresented: $isShowingPosts){
PostsPopup(isPresented: $isShowingPosts, storedMessages: $storedMessages)
PostsPopup(isPresented: $isShowingPosts)
.environmentObject(messageState)
}

}
}


}


//struct HomePageView: View {
// @State private var isShowingProfile = false
Expand Down
8 changes: 1 addition & 7 deletions app/newHere1/newHere/Message.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,12 @@ class Message {
var id: String
var user_id: String
var location: CLLocation
var author: String
var messageStr: String

init(id:String, location:CLLocation, author: String, messageStr: String) {
init(id:String, location:CLLocation, messageStr: String) {
self.id = id
self.user_id = "653d51478ff5b3c9ace45c26"
self.location = location
self.author = author
self.messageStr = messageStr
}

func displayMessage() -> String {
return "Author: \(author)\n\(location.coordinate.latitude.description), \(location.coordinate.longitude.description), \n\(messageStr)"
}
}
11 changes: 7 additions & 4 deletions app/newHere1/newHere/Post.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ struct MessageResponse: Codable {

struct PostsPopup: View {
@Binding var isPresented: Bool
@Binding var storedMessages: [Message]
// @Binding var storedMessages: [Message]

@State private var noteMessage: String = "This is your message!"

Expand All @@ -37,7 +37,7 @@ struct PostsPopup: View {
let senderName: String = "Username"

@EnvironmentObject var locationDataManager: LocationDataManager

func postMessage(user_id: String, text: String, visibility: String, completion: @escaping (Result<MessageResponse, Error>) -> Void) {
// make sure you can get the current location
if let currentLocation = locationDataManager.location {
Expand Down Expand Up @@ -136,9 +136,12 @@ struct PostsPopup: View {


do {
let newMessage = try Message(id: response._id, location: response.location.toCLLocation(), author: "Anna", messageStr: response.text)
let newMessage = try Message(
id: response._id,
location: response.location.toCLLocation(),
messageStr: response.text)
// Use newMessage here
self.storedMessages.append(newMessage)
// self.storedMessages.append(newMessage)

messageState.currentMessage = newMessage

Expand Down
9 changes: 6 additions & 3 deletions app/newHere1/newHere/api_call.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct UserMessage: Codable {
let coordinates: [Double]
}

let location: Location
let location: GeoJSONPoint
let _id: String
let user_id: String
let text: String
Expand All @@ -25,7 +25,7 @@ struct UserMessage: Codable {
let replies: [String]
}

func getUserMessages(userId: String, completion: @escaping (Result<[UserMessage], Error>) -> Void) {
func getUserMessages(userId: String, completion: @escaping (Result<[MessageResponse], Error>) -> Void) {
let urlString = "https://here-swe.vercel.app/user/\(userId)/messages"

guard let url = URL(string: urlString) else {
Expand Down Expand Up @@ -55,8 +55,11 @@ func getUserMessages(userId: String, completion: @escaping (Result<[UserMessage]
}

do {
let messages = try JSONDecoder().decode([UserMessage].self, from: data)
let messages = try JSONDecoder().decode([MessageResponse].self, from: data)
completion(.success(messages))



} catch {
completion(.failure(error))
}
Expand Down

0 comments on commit 7ad199a

Please sign in to comment.